Wednesday 23 October 2019

Should data validation be handled within the definition of a class, or before creating a new instance of the class with that data?

Let's say you have a class that will be the structure of some data that you will then insert into a database with a function within the class like this:class Player { constructor (playerName) { this.playerName = playerName; } insert() { connection.query( "INSERT INTO Players (playerName) VALUES (?)", [this.playerName] ); } } const userInput = getUserInput().toString(); const player = new Player(userInput); player.insert(); Now let's say you decide names can only be 24 characters long and want to handle the validation somewhere in this block of code.Should you validate the data before creating the new Example instance, or should you create a function to validate the input inside the class definition?

Submitted October 24, 2019 at 02:27AM by g3t0nmyl3v3l

No comments:

Post a Comment