When I have a method that uses properties of the containing class, but I also need to use that method without having an object of that class, is it OK to make a static overload of that method?
A simple example:
public class Parent {
public string LastName;
//... constructor etc.
public Child[] GetChildren() {
// Retrieve Children (from DB) by LastName
return DB.GetChildren(LastName);
}
}
In this example the method GetChildren
uses a property of the containing class (Parent.LastName
) to query the database.
This works fine when I have a Parent
object, but what if I only have a LastName
? My solution would be to create a static overload that takes a lastName
as an argument:
public Child[] GetChildren() {
return GetChildren(LastName);
}
public static Child[] GetChildren(string lastName) {
// Retrieve Children (from DB) by LastName
return DB.GetChildren(lastName);
}
But is this the right way to do it? I can imagine that this can become very messy when there are a lot of "duplicate" methods in the same class. What's the best way to structure this code without everything becoming cluttered?
Edit: I have seen this question, which overlaps with mine, but I'm curious how code should be structured when there are many methods where this is the case (instead of just one or two). Should code be split up, for example?
Aucun commentaire:
Enregistrer un commentaire