Data Objects vs fields

  • Thread starter Thread starter Kuma
  • Start date Start date
K

Kuma

Beginner question. Are there any advantages or disadvantages to using
a custom data object to group logically linked objects vs using simple
fields? For example (don't beat me up too much it's an example).

Instead of this:

public class Chat
{
private string Message { get; set; }
private string Name { get; set; }
private DateTime When { get; set; }
public Chat(string a, string b, DateTime c)
{
Message = a;
Name = b;
When = c;
DoSomeThing1(A, B, C);
DoSomeThing2(A, B, C);
DoSomeThing3(A, B, C);
}
}

Would there be a reason why using the ChatMessage object below is good
or bad?
Is it just a personal preference?

public class ChatMessage
{
private string Message { get; set; }
private string Name { get; set; }
private DateTime When { get; set; }
public ChatMessage(string a, string b, DateTime c)
{
Message = a;
Name = b;
When = c;
}
}

public class Chat
{
public Chat(string a, string b, DateTime c)
{
ChatMessage msg = new ChatMessage(a, b, c);
DoSomeThing1(msg);
DoSomeThing2(msg);
DoSomeThing3(msg);
}
}
 
Kuma said:
Beginner question. Are there any advantages or disadvantages to using
a custom data object to group logically linked objects vs using simple
fields? For example (don't beat me up too much it's an example).

Instead of this:

public class Chat
{
private string Message { get; set; }
private string Name { get; set; }
private DateTime When { get; set; }
public Chat(string a, string b, DateTime c)
{
Message = a;
Name = b;
When = c;
DoSomeThing1(A, B, C);
DoSomeThing2(A, B, C);
DoSomeThing3(A, B, C);
}
}

Would there be a reason why using the ChatMessage object below is good
or bad?
Is it just a personal preference?

public class ChatMessage
{
private string Message { get; set; }
private string Name { get; set; }
private DateTime When { get; set; }
public ChatMessage(string a, string b, DateTime c)
{
Message = a;
Name = b;
When = c;
}
}

public class Chat
{
public Chat(string a, string b, DateTime c)
{
ChatMessage msg = new ChatMessage(a, b, c);
DoSomeThing1(msg);
DoSomeThing2(msg);
DoSomeThing3(msg);
}
}

Its an interesting question. I can't see any strong reason why this
approach would be bad. It is unusual, although I have seen in the past
(can't remember where) some musings on whether all fields should in fact be
automatic properties.

Personally, simply because it is unusual is enough to make it a bad thing to
do unless there was some other overriding reason.

In the specific case above the class appears odd, one would expect the
properties to be readonly publicly. In which case automatic properties
would be the way to go:-

public class ChatMessage
{
public string Message { get; private set; }
public string Name { get; private set; }
public DateTime When { get; private set; }
public ChatMessage(string a, string b, DateTime c)
{
Message = a;
Name = b;
When = c;
}
}
 
Back
Top