I’m just wondering, is there any considerations that should be taken for class variables that are going to hold information that is used in a database connection?
Like, basically, should I be using the public keyword in front of variable that will hold database information or does this create security concerns? What do you do?
All in all, it doesn’t really matter, as long as the variable isn’t static, it makes no difference as far as creating new instances of that class (and multiple connections) is concerned.
Though, on the whole, I must say it’s probably a good idea to assign the actual connection to a
privateorprotectedproperty, and add a publicgeConnection()member-function if ever you might need it.The reason for this is simple: Objects should be written in such a way that they can be reused. If your code is going to be used by somebody who doesn’t really know all that much about databases, your class could (and should) shield that person from having to deal with all the abstract stuff that might not be familiar to that user.
It stands to reason, therefore, that your class hides the actual connection, so that other code can’t interact with the db connection directly.
In short: although assigning the connection to a public property doesn’t really make a difference as far as security towards the outside world is concerned, it does make your code more error prone, in case a colleague uses it and inadvertently assigns an array/object to the property that holds the db connection…