3

Can a method be considered a mutator method if it is more complex than just setting a value?

I know what a setter method is. An Account class might have a method: public void setAccountNumber(String accountNumber) or something like that that very simply takes an input, and sets an object's instance value to the input value.

But what about more complex methods that modify the object. Would any method that modifies the object be considered a mutator?

What if there was a boolean value: loggedIn

and a method public boolean logIn(String username, String password) that verified the given username and password, and then set the loggedIn value to true if correct.

I wouldn't consider this a setter method, but would it still be considered a mutator?

Or what about a move() method that modifies the location of a Sprite object in a grid, but the new location would depend on its current location, direction, whether moving would move it outside the bounds of the grid etc.? Or an addInterest() method that potentially changes the balance of a BankAccount object (or not depending on whether the account earned interest and the interest rate was greater than 0).

Is anything that can modify the object's instance data considered a mutator, or is the term mutator more specific than that?

[NOTE: I'm familiar with the term mutator, and I've seen stackoverflow posts addressing the basic definition of a mutator, but this question is different because I am asking whether a more complex method that does more than just passing a value to assign to an instance variable value would be considered a mutator. I know that the setter method public void setBalance(double value) would be a mutator. I'm less clear about whether public void move() would be considered a mutator.]

Tim
  • 31
  • 3
  • And what if `logIn()` reads username and password off the object, sets the value of `loggedIn`, and after that returns the value of `loggedIn`? It would be doing both or more. Would we have to classify it as well? – ernest_k Aug 21 '18 at 15:45
  • 4
    Short answer: yes, anything that may modify an object’s state is a mutator. – VGR Aug 21 '18 at 15:51
  • Check out the definition of a pure function. https://en.wikipedia.org/wiki/Pure_function With classes, to be immutable, you'd have to make a copy of the class with the new value. See how the String class works and why we have classes like StringBuffer. https://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning – randal4 Aug 21 '18 at 15:54
  • 1
    "I wouldn't consider this a setter method, but would I still consider it a mutator?" Only you can answer that question. – TylerH Aug 21 '18 at 19:22
  • Possible duplicate of [Java - Using Accessor and Mutator methods](https://stackoverflow.com/questions/15711442/java-using-accessor-and-mutator-methods) – K.Nicholas Aug 23 '18 at 00:39

0 Answers0