views:

53

answers:

3

How do restrict access to a class property to within the same namespace? Consider the following class. The Content class cannot Publish itself, instead the ContentService class will do a few things before changing the state to published.

public class Content : Entity, IContent
    {
        public string Introduction { get; set; }

        public string Body { get; set; }

        public IList<Comment> Comments { get; set; }

        public IList<Image> Images { get; private set; }

        public State Status { get; } 
    }

public class ContentService
    {
        public IContent Publish(IContent article)
        {
            //Perform some biz rules before publishing   
            article.Status = State.Published;
            return article;
        }
    }

How can i make it so only the ContentService class can change the state of the article?

Are there any deisng patterns to help me deal with this?

A: 

Java has the notion of "package visible" or "package private". This is in fact the default for anything where you don't specify a visibility (private or public). For some reason, almost no one ever uses this.

Aaron Digulla
A: 

Declare ContentService as a friend?

Alternatively, Java has an access modifier that amounts to "package-private".

aib
A: 

You can use the "internal" access modifier so that only classes within the same Assembly can modify the Content class's State member (but everyone even in other assemblies can GET the value).

public State Status { get; internal set; } 

So now ContentService can set the state because it is in the same Assembly, but outside callers can only get the state (they're not allowed to set it).

Clay Fowler