I'm using C# but the problem could also be with Java. I have an object in the flow that is muted for setting up some properties during the flow of the program. Let say

public class Person {
  public string name {get; set;}
  public string surname {get; set;} 
}
public class Citizen {
  public string name {get; set;}
  public string surname {get; set;}
  public string country {get; set;}
  ....
}

actually the flow is to create Citizen with just name and surname and enriched the fields with methods..ect but the problem is that after some methods and some steps, we doesn't know which field is initialized or not. Maybe we would use two objet like create Person and recreate a more specialized object Citizen with the fields we want to enrich and do a copy of each Person fields in Citizen. But we can have performance issues, can we do that without creating many new objects at each steps of the program ?

有帮助吗?

解决方案

Performance problems should be handled when you have them. Of course, if you know that the code will be executed in a time-critical path, you don't want to write it in a wasteful way to start with, but you can't really optimize before you've got an actual performance issue, and even then micro-optimization is very rarely the right approach. Adding one object does not add 10 ms execution time, depending on language and runtime system it's most likely to be in the microseconds or nanoseconds area. Note that this does not apply to networked services, there each service request might add a significant latency, but we're talking about objects here, not network service interfaces.

That said, your class design already shows a clear problem. A person can be a citizen of some country, can have dual citizenship, can be stateless, but still is a person. Citizen therefore is a role that a person can have, or a relationship between a person and a country, but not a subclass of Person nor a completely unrelated class with person attributes. A proper class definition might look like

public class Person {
  public string name {get; set;}
  public string surname {get; set;} 
}
public class Country {
  public string name {get; set;}
  ....
}
public class Citizen {
  public Person person {get; set;}
  public Country country {get; set;}
  ....
}

If you build your data incrementally, you would then create a Person object first with all the attributes that belong to it, and create a Citizen role object only later when the nationality of the person is known (and you might create a second Citizen objekt when you learn that the person has dual citizenship.)

许可以下: CC-BY-SA归因
scroll top