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!

c#
Posted by: Matt Hamilton
Last revised: 10 Oct, 2024 01:39 PM History

Trackbacks

Comments

23 Apr, 2012 03:43 AM @ version 2

Why wouldn't you use a struct?

23 Apr, 2012 07:31 AM @ version 2

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.

19 May, 2012 04:43 AM @ version 2

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.

No new comments are allowed on this post.