I've seen a lot of both and depending on who the developer is, either way may be the preferred method. As far as I can tell, there is no standard method. I'm talking about the way instance variable values are set when the class is created.
Constructor Method:
Code:public function __construct ( string $dsn, string $username, string $password) {
$this->__dsn = $dsn;
$this->__username = $username;
$this->__password = $password;
}
Setter Method:
I prefer passing variables to the constructor. It is easier to read and less lines of code for both the object developer and the person creating the object.Code:public function setDsn($dns) {
$this->__dsn = $dsn;
}
public function setUsername($username) {
$this->__username = $username;
}
public function setPassword($password) {
$this->__password = $password;
}
I understand there may be some instances where having it passed to the constructor and using the same setters may be beneficial, such as when you want to allow data to be changed, but for this discussion I am strictly speaking of setting the data when the class is first created.
Which method do you prefer? Why?
Constructors, but I think that's because they're easy to work with in C++. Especially for some types of data, there can be a serious performance hit if you use a constructor to create something large, and then redefine it with setters.
I prefer a third way, hah. In C# it is called Object Initializers. You do not have to create a constructor (default one will do) and you do not need to create methods (or property accessors). Just use a default constructor and set whatever properties you want.
Here is some C# example.
Code:class Program
{
class PersonalInfo
{
public string FullName;
public DateTime DateOfBirth;
public int Age;
}
static void Main(string[] args)
{
PersonalInfo me = new PersonalInfo()
{
FullName = "Arek Bulski",
DateOfBirth = new DateTime(2009, 01, 02),
Age = 21,
};
/// This is me. No constructor required. Neither
/// any method or property set accessor. :)
}
}
proudly presenting my personal website and game website: F1Simulation. a thrilling Managed DirectX racing game... also my Ask Me
look at my tutorials about cropping images and Mono: bundling Mono with programs and lambda expressions
One vote for constructors..
Posted via CodeCall Mobile
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks