Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to create object

Tags:

This seems to be very stupid and rudimentary question, but i tried to google it, but couldn't a find a satisfactory answer,

public class Person {     public string Name { get; set; }     public int Age { get; set; }     public Person(){}     public Person(string name, int age)     {         Name = name;         Age = age;     }     //Other properties, methods, events... } 

My question is if i have class like this, what is the best way to create an object?

Person p=new Person("abc",15) 

OR

Person p=new Person(); p.Name="abc"; p.Age=15; 

What is the difference between these two methods and what is the best way to create objects?

like image 267
DevT Avatar asked Feb 07 '13 08:02

DevT


People also ask

What is the best way to create an object in JavaScript?

Creating a JavaScript ObjectCreate a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .

How many ways we can create object?

In Java, we can create objects with 6 different methods which are: By new keyword. By newInstance() method of Class class. By newInstance() method of constructor class.


1 Answers

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person {     public string Name { get; set; }     public int Age { get; set; }     public Person(){}     public Person(string name, int age)     {         Name = name;         Age = age;     }     //Other properties, methods, events... } 

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

public class Person {     public string Name { get; private set; }     public int Age { get; private set; }      public Person(string name, int age)     {         Name = name;         Age = age;     }     //Other properties, methods, events... } 

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

like image 89
davioooh Avatar answered Oct 22 '22 02:10

davioooh