I want to create maintainable code, but this inheritance situation is causing me problems.
The issue is with my 2nd database helper class named InitUserExtension.
Since UserExtension inherits from User, I have to make sure that I mirror any changes in my InitUser helper to InitUserExtension.
I really don’t like this as its prone to bugs, what’s the solution?
My class definitions:
public class User { public string Name {get; set; } public string Age { get; set; } } public class UserExtension : User { public string Lastname {get; set; } public string Password {get; set; } }
My database helpers:
public static SqlDataReader InitUser(SqlDataReader dr) { User user = new User(); user.Name = Convert.ToString(dr['name']); user.Age ... } public static SqlDataReader InitUserExtension(SqlDataReader dr) { UserExtension user = new UserExtension(); // note: mirror attributes from User user.Name = Convert.ToString(dr['name']); user.Age ... user.Lastname = Convert.ToString(dr['lastname']); user.Password = ....; }
How about moving the processing of Name etc into a method (accepting either a User or a T : User), and call that from both?
As an alternative, you could reduce the line count, but increase the complexity, using generics: