patterncsharpMinor
Changing the type of an object inside a method?
Viewed 0 times
themethodtypechangingobjectinside
Problem
First off, this is not my code. I'm curious what everyone thinks about changing the type of an object inside of a method then modifying the properties of the cast type. I wanted to use composition to build up a patient, but this is the recommend path. I'm probably wrong which is why I wanted 3rd party feedback. Or maybe we just have different coding styles...
for reference
//
//
// Person/Patient Builder
public static void BuildUpPersonOrPatient(Person person, Dictionary row)
{
person.FirstName = row["FirstName"];
person.LastName = row["LastName"];
Patient patient = person as Patient;
if (patient != null)
{
patient.PatientID = row["PatientID"];
}
}for reference
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Patient : Person
{
public string PatientID { get; set; }
}//
//
Solution
It stead of having a static method the basically does what polymorphism could do for you use polymorphism.
and then where ever you call
do this instead
I've added an access modifier to the setters because unless you have a reason to be able to change those fields from outside the object you should encapsulate the possibility of chaning the state of an object. (It's surprising how seldom you have a modeling reason for that and not just a "for conviniece" reason)
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public virtual void InitializeFromDictionary(Dictionary row)
{
FirstName = row["FirstName"];
LastName = row["LastName"];
}
}
public class Patient : Person
{
public string PatientID { get; private set; }
public override void InitializeFromDictionary(Dictionary row)
{
base.InitializeFromDictionary(row)
PatientID = row["PatientID"];
}
}and then where ever you call
BuildUpPersonOrPatient(p,row);do this instead
p.InitialieFromDictionary(row);I've added an access modifier to the setters because unless you have a reason to be able to change those fields from outside the object you should encapsulate the possibility of chaning the state of an object. (It's surprising how seldom you have a modeling reason for that and not just a "for conviniece" reason)
Code Snippets
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public virtual void InitializeFromDictionary(Dictionary<string, string> row)
{
FirstName = row["FirstName"];
LastName = row["LastName"];
}
}
public class Patient : Person
{
public string PatientID { get; private set; }
public override void InitializeFromDictionary(Dictionary<string, string> row)
{
base.InitializeFromDictionary(row)
PatientID = row["PatientID"];
}
}BuildUpPersonOrPatient(p,row);p.InitialieFromDictionary(row);Context
StackExchange Code Review Q#56687, answer score: 7
Revisions (0)
No revisions yet.