0

I often write code which makes an object and then use static methods in static classes to manipulate said object.

Am I missing the point of OOP? How do I know whether I'm thinking in the OOP mind set? I doubt I am...

Dan Pichelman
  • 13,773
  • 8
  • 42
  • 73
Dan Savage
  • 59
  • 3
  • 2
    The style you describe is probably more of a *functional* style than an object-oriented one. It's a perfectly valid technique, especially if you are returning new objects from your methods. – Robert Harvey Jul 24 '15 at 14:43
  • see also: [Significant amount of the time, I can't think of a reason to have an object instead of a static class. Do objects have more benefits than I think?](http://programmers.stackexchange.com/questions/242940/significant-amount-of-the-time-i-cant-think-of-a-reason-to-have-an-object-inst) – gnat Jul 24 '15 at 14:46

1 Answers1

1

Yes, you are missing OOP principles in your coding. OOP is not about bearing primitive types, OOP is about having an object that has responsibilities(methods essentially).

GRASP Principles are a good start to learn where which method belongs in OOP.

In OOP you want to treat most instances as objects that have responsibilities and instance fields(instance specific variables). However, sometimes(and I mean sometimes) you would find a need to have a static class, which is perfectly valid as long as you really sure this class has no need for an instance. But before you settle down with creating one, think - "Am I missing an object?".

Your Functional Way:

var alice = new Person("Alice");

ChangeName(alice, "John");

// Somewhere in your static code
function ChangeName(Person person, string name) {
    person.name = name;
}

OOP Way:

var alice = new Person("Alice");
alice.ChangeName("John");

public class Person {
    private _name;    

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

    public void ChangeName(string name) {
        _name = name;
    }
}
Alexus
  • 2,368
  • 15
  • 24
  • I'm sorry but in what universe could the first code you wrote be considered "functional" in any way at all? – sara Jun 28 '16 at 15:31