OOP Anti-Pattern – Is Creating New Instance in Class Property Bad?

factory-methodobject-oriented

I have a class called Heading that does a few things, but it should also be a able to return the opposite of the current heading value, which finally has to be used via creating a new instance of the Heading class itself.

I can have a simple property called reciprocal to return the opposite heading of the current value and then manually create a new instance of the Heading class, or I can create a method like createReciprocalHeading() to automatically create a new instance of the Heading class and return it to the user.

However, one of my colleagues recommended me to just create a class property called reciprocal that returns a new instance of the class itself via its getter method.

My question is: Isn't it an anti-pattern for a property of a class to behave like that?

I particularly find this less intuitive because:

  1. In my mind, a property of a class should not return a new instance of a class, and
  2. The name of the property, which is reciprocal, doesn't help the developer to fully understand its behaviour, without getting help from the IDE or checking the getter signature.

Am I being too strict about what a class property should do or is it a valid concern? I have always tried to manage the state of the class via its fields and properties and its behaviour via its methods, and I fail to see how this fits to the definition of the class property.

Best Answer

Its not unknown to have things like Copy() or Clone() but yes I think you are right to be worried about this one.

take for example:

h2 = h1.reciprocal
h2.Name = "hello world"
h1.reciprocal.Name = ?

It would be nice to have some warning that the property was a new object each time.

you might also assume that:

h2.reciprocal == h1

However. If your heading class was an immutable value type then you would be able to implement these relationships and reciprocal might be a good name for the operation