256

In OOP, sooner or later, you are going to make a subclass of a class This is wrong. Not every class is meant to be subclassed and some statically typed OOP languages even have features to prevent it, e.g., final (Java and C++) or sealed (C#). it is good to understand and being able to modify the implementation completely. No, it's not. It's good for a ...


230

Because as you say, protected still leaves you with the ability to "modify the implementation completely". It doesn't genuinely protect anything inside the class. Why do we care about "genuinely protecting" the stuff inside the class? Because otherwise it would be impossible to change implementation details without breaking client code. Put another way, ...


122

Layers, modules, indeed architecture itself, are means of making computer programs easier to understand by humans. The numerically optimal method of solving a problem is almost always an unholy tangled mess of non-modular, self-referencing or even self-modifying code - whether it's heavily optimized assembler code in embedded systems with crippling memory ...


66

A lot of people think that unit testing is method-based; it's not. It should be based around the smallest unit that makes sense. For most things this means the class is what you should be testing as a whole entity. Not individual methods on it. Now obviously you will be calling methods on the class, but you should be thinking of the tests as applying to ...


63

The fundamental motivation is this: You want to be able to rip an entire layer out and substitute a completely different (rewritten) one, and NOBODY SHOULD (BE ABLE TO) NOTICE THE DIFFERENCE. The most obvious example is ripping the bottom layer out and substituting a different one. This is what you do when you develop the upper layer(s) against a ...


57

A benefit is that the compiler can let you know if you accidentally type "ADRESS" or "FEILDSET", and letting you fix it immediately instead of behaving in a nonsensical way at runtime. While the benefit is much more useful in statically typed languages than dynamic, it is still useful even if it is a runtime error as you will get message indicating a ...


56

I hate how encapsulation is always framed as preventing unauthorized access. If this were the best way to think of it, immutability would indeed eliminate most of the need for encapsulation. In fact, immutability does eliminate many cases of overzealous encapsulation, where the only purpose of the encapsulation was to keep the bumbling callers out. ...


51

The fact that your data-gathering methods are complex enough to merit tests and separate enough from your primary goal to be methods of their own rather than part of some loop points to the solution: make these methods not private, but members of some other class that provides gathering/filtering/tabulating functionality. Then you write tests for the dumb ...


51

The question Casting your question to real life: Is it okay for your doctor to post your private medical records publicly to Facebook, provided no one (other than you) is able to change it? Is it okay for me to let strangers in your house, provided they can't steal or damage anything? It's asking the same thing. The core assumption of your question is that ...


48

Calling a class method with some class variables is not necessarily bad. But doing so from outside the class is a very bad idea and suggests a fundamental flaw in your OO design, namely the absence of proper encapsulation: Any code using your class would need to know that len is the length of the array, and use it consistently. This goes against the ...


44

Units I think I can pinpoint exactly where the problem started: I figured, I'll need a method that finds all the non-numerical fields in a line. This should be immediately followed with asking yourself "Will that be a separate testable unit to gatherNonNumericColumns or part of the same one?" If the answer is "yes, separate", then your course of ...


38

I remember having a similar argument with my lecturer when learning C++ at university. I just couldn't see the point of using getters and setters when I could make a variable public. I understand better now with years of experience and I've learned a better reason than simply saying "to maintain encapsulation". By defining the getters and setters, you will ...


37

Within software development, privacy (of software entities) is usually defined as restricting access to that variable/function/method. If a variable is private, then only functions or methods that belong to the same class or module are allowed/supposed to access that variable. As you see, privacy here is completely unrelated to which developer is writing ...


34

I'm generally in favor of nested functions, especially in JavaScript. In JavaScript, the only way to limit a function's visibility is by nesting it inside another function. The helper function is a private implementation detail. Putting it at the same scope is akin to making a class' private functions public. If it turns out to be of more general use, it's ...


34

Yes, private fields are absolutely necessary. Just this week I needed to write a custom dictionary implementation where I controlled what was put into the dictionary. If the dictionary field were to be made protected or public, then the controls I'd so carefully written could have been easily circumvented. Private fields are typically about providing ...


33

You can write code that looks like this: if (pet.type() == dog) { pet.bark(); } else if (pet.type() == cat) { pet.meow(); } else if (pet.type() == duck) { pet.quack() } or you can write code that looks like this: pet.speak(); If what varies is encapsulated then you don't have to worry about it. You just worry about what you need and whatever you'...


33

There are may things with the class that I would do differently, but to answer the direct question, my answer would be yes, it is a bad idea My main reason for this is that you have no control over what is passed to the add function. Sure you hope it is one of the member arrays, but what happens if someone passes in a different array that has a smaller ...


32

Encapsulation could mean that you hide the actual storage of immutable data. E.g.: class Color { private readonly uint argb; public byte Blue => (byte)(argb & 0xFF); public Color(byte red, byte green, byte blue, byte alpha) { argb = alpha << 24 | red << 16 | green << 8 | blue; } } The interface (the constructor and ...


31

Neither is generally better than the other. It's a judgment call you have to make on a case-by-case basis. But in practice, when you're in a position that you can actually make this decision, it's because you get to decide which layer in the overall program architecture should be breaking the object up into primitives, so you should be thinking about the ...


30

By wrapping a third party library you add an additional layer of abstraction on top of it. This has a few advantages: Your code base becomes more flexible to changes If you ever need to replace the library with another one you only need to change your implementation in your wrapper - in one place. You can change the implementation of the wrapper and don't ...


29

Personally, I feel you went to far into the implementation mindset when you wrote the tests. You assumed you would need certain methods. But do you really need them to do what the class is supposed to do? Would the class fail if someone came along and refactored them internally? If you were using the class (and that should be the mindset of the tester in my ...


27

Object-Oriented Data Abstraction is all about Behavioral Abstraction. The implementation details are hidden behind a behavioral interface, i.e. an interface that does something. A variable is not behavior, it is state. A getter or setter is just a variable in disguise. The question is: "what does a Point do", not "what state does it have". For example, ...


26

I guess they had a good idea of what an average programmer would do. And by average programmer I mean one who is not really good at programming, but gets the job anyway because there are not enough good ones and they are expensive. If they made "public" access the default one, most programmers would never bother to use anything else. The result would be a ...


23

Coupling ClassA relies upon the interface only, delegating this responsibility of passing the classB object elsewhere This is the idea. If you are separating ClassA from ClassB by the use of an interface ISomeInterface... ensuring (ClassA) doesn't know ClassB Then you do not want ClassA to ...


22

Enums are useful for situations where you have a fixed set of values/entities that are sensible. They are self-documenting and allow the compiler validate things that would otherwise be left to run-time. They should never be used if the set of meaningful values is not known or not strictly limited. A more useful example would be something like HTTP ...


22

Your confusion is probably caused by focussing on meaningless class and interface names, with no real usage scenario behind it. So better let us make a concrete example (I prefer C#, but it is not really different in other languages like Java). The IComparable interface in the .NET framework looks (simplified) like this: interface IComparable { int ...


21

If the getter/setter simply mirrors the value then there is no point in having them, or in making the value private. There is nothing wrong with making some member variables public if you have a good reason. If you are writing a 3d point class then having .x, .y ,.z public makes perfect sense. As Ralph Waldo Emerson said, "A foolish consistency is the ...


21

Yes, you are missing something. Encapsulation is often described with metaphors of "hiding" or acting "defensive", as if client programmers were your enemy and you had to act stealthily and sneakily to defend yourself against their evil intentions. That is sometimes helpful; for instance, if you program extremely popular frameworks that have to maintain ...


20

Here is what Robert C. Martin (the "clean code" guy) would do: http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop So I guess he would split up your isCreditOk function further like this public int calculateOrderPrice(Set<Item> items) { int orderPrice=0; for(Item item: items){ orderPrice+=items....


Only top voted, non community-wiki answers of a minimum length are eligible