Data Management - Read Data

I am working on some project in C # and I ran into the following problem:

I have some data type classes, for example, the Person class, which stores information about a person.

In addition, I have a DataManager class that is responsible for managing people in my program. If you want to add, receive, find or delete a person, you would only do this through the DataManager class.

The problem is that I do not want anyone other than the DataManager class to be able to modify Person objects. If someone calls DataManager.getPerson(int ID), for example, they will receive a Person object and be able to use the setter functions of this Person object to change its contents (first name, last name, identifier, etc.).

I want to avoid this. I want only the DataManager class to be able to modify Person objects (using methods such as DataManager.changeFirstNameForPerson(int ID, string name)).

What is the best class structure that can achieve this?

+3
source share
5 answers

Well, you can never stop people from changing values ​​by 100%. They could always just go through reflection.

But, from the point of view of the API, you can make all getters of the Person class public, and all internal setters - internal. As long as the Person and DataManager classes are in the same assembly, the DataManager will be able to access the setters, but other applications that reference the assembly cannot.

public class Person
{
    public string Fname { get; internal set; }
}


public class DataManager
{
    public void ChangeNameForPerson(int id, string fname)
    {
        Person p = Person.GetById(id);
        // Inside the same assembly.  Setter is accessible
        p.Fname = fname;
    }
}

Outside of the assembly, you will get the following:

Person p = DataManager.GetPerson(1);
p.Fname = "asdf"; // Compile time error
DataManager.ChangeNameForPerson(1, "asdf"); // Works fine
+2
source

, spring :

1 - Person DataManager Person

2 - Person Person DataManager

+1

get/set accessors Person , . DataManager , , .

+1

Person ; .. readonly getters, . .

0

- Person DataManager (.. DataManager.Person), Person :

public class Person
{
    private DataManager.Person person;

    public Person(Datamanager.Person person)
    {
        this.person = person
    }

    public int ID
    {
        get { return person.ID; }
    }

    ...
}

Then in your DataManager class, you will do something like:

public Person GetPerson(int id)
{
    DataManager.Person person = // get the person by ID
    return new Person(person);
}

Now the external code has read-only access to the Person class, but it cannot get a read / write link to DataManager.Person.

-1
source

Source: https://habr.com/ru/post/1752868/


All Articles