简体   繁体   中英

Is it bad practice to modify the variable within a method?

Which method style is better? Is it generally bad practice to modify the variable within a method?

public class Person
{
   public string Name { get; set;}
}

//Style 1
public void App()
{
    Person p = new Person();
    p.Name = GetName();
}
public string GetName()
{
   return "daniel";
}

//Style 2
public void App()
{
    Person p = new Person();
    LoadName(p)
}
public void LoadName(Person p)
{
   p.Name = "daniel";
}

There are times when both styles may make sense. For example, if you're simply setting the name, then perhaps you go with the first style. Don't pass an object into a method to mutate one thing, simply retrieve the one thing. This method is now more reusable as a side benefit. Think of it like the Law of Demeter or the principle of least knowledge.

In other cases, maybe you need to do a wholesale update based on user input. If you're displaying a person's attributes and allowing the user to make modifications, maybe you pass the object into a single method so that all updates can be applied in one spot.

Either approach can be warranted at different times.

I think the code is more clear and readable when methods don't change objects passed. Especially internal fields of passed object.
This might be needed sometimes. But in general I would avoid it.

Updated based on comment (good point)

I agree with Anthony's answer. There are times when both styles may make sense.

Also, for more readability you can add the LoadName function in person class.

public void App()
{
    Person p = new Person();
    p.LoadName(); //If you need additional data to set the Name. You can pass that as Parameter
}

I agree with Ron. Although your particular example could be slightly contrived for posting reasons, I would have a public getter for Name, and a private setter. Pass the name to the constructor, and the Name property will get set there, but afterwards can no longer be modified.

For example:

public class Person
{
    public string Name { get; private set; }

    public Person( string name)
    {
        Name = name;
    }
}

You are accessing the data using properties which technically is by a methods. What you are worried is property accessing iVar or internal variable. There reason why it is generally bad to allow access of iVar is because anyone can modify the variables without your knowledge or without your permission, if its through a methods (properties), you have the ability to intercept the message when it get or set, or prevent it from getting read or write, thus it is generally said to be the best practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM