Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

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.

Declare ContentService as a friend?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top