Internal Constructors for Read Only Classes?
Let's say you're designing a class library, and you have a class like this:
public class Person
{
public string Name { get; internal set; }
public int Age { get; internal set; }
public string Details { get; internal set; }
}
You're only ever returning Person
objects from your API. There's no reason for the user of your API to ever change the properties, so you've made their setters internal, effectively making them read only.
Is there any point in leaving the default (public) constructor there? Why would an end user need to create an instance of your Person
class if they can't change it? Would it make more sense to make the constructor internal too?
Or perhaps a protected constructor and property setters. That way if developers needed to create instances of Person
for testing purposes (like mocking) then they could always derive from it.
Taking it one level further: Is there any reason to surface the class at all? Why not return an IPerson
interface and make the entire class internal?
What do you think? Weigh in!
Trackbacks
- Dew Drop – April 19, 2012 (#1,309) | Alvin Ashcraft's Morning Dew | http://www.alvinashcraft.com/2012/04/19/dew-drop-april-19-2012-1309/
No new comments are allowed on this post.
Comments
Aaron Powell
Why wouldn't you use a struct?
Matt Hamilton
One of the classes in Budgie (
TwitterStatus
) is self-referential, so a struct wasn't an option. I guess I could've used a nullable struct but it seemed easier to use a class.Sam Naseri
Why to restrict classes? making properties private does not add any value, but it would be restrictive. I guess the purpose of private and public thing is to separate internal/external of an object in a way that we know how to deal with an object without putting the object in an invalid state. Having said that I disagree with privatization just to restrict users.