r/programming • • May 05 '19

10 OOP Design Principles Programmer Should Know

https://hackernoon.com/10-oop-design-principles-every-programmer-should-know-f187436caf65
2 Upvotes

44 comments sorted by

25

u/glacialthinker May 05 '19 edited May 05 '19

I tend to hate OOP because of the poor quality of code which results: 10% of the code being relevant to the problem, the rest being boilerplate, excessive interface and encapsulation fluff (which also has to change as the program evolves anyway), redundancy because of object hierarchies tied to types/data or functionality hidden by abstraction, and more...

However, this set of principles (the article) can lead to much better object-oriented code, and most of them can apply to programming in general. I'd rather work with programmers following these principles (though reserving heavy encapsulation for library or external interfaces) than working with a tool-belt full of design-patterns.

7

u/[deleted] May 05 '19

I think people are going to start hating FP a lot more if it becomes mainstream and legions of unskilled, un-interested programmers create legacy applications with it.

2

u/glacialthinker May 05 '19

Yeah, this is a fear I have, but I have some hope that the possible disaster is of lesser degree? Easier to refactor. Less tangled. Maybe we'll see!

2

u/ScientificBeastMode May 06 '19

I hope not.

But on the other hand, FP is usually different from OOP in all the right ways, IMO. In particular, the ability to rapidly compose complex operations from simple function primitives is extremely useful for both code reuse and refactoring.

The nice thing is that most of your code doesn’t have to care what your data looks like, since you can just replace one or two functions if the shape of your data changes.

That, to me, is the biggest pain point in OOP. Both paradigms have abstract type systems in different forms. But in OOP, it’s so tightly coupled with your data. And the shape/content of your data is the most likely thing to change over time.

Idk though, getting over the hump of learning the FP paradigm was challenging. And I’m sure it will be that way for many others down the road.

2

u/Zardotab May 06 '19

I've yet to see practical examples of FP improving typical code. It often assumes unrealistic conditions or conditions only true in a niche. It's also hard to debug the innards of FP, or at least learning how to debug the innards takes an excessive amount of time. I'm still open to the idea, but have yet to see strong justification for typical environments.

1

u/ScientificBeastMode May 06 '19

I definitely think it depends on the company, the team composition, the codebase, and the languages under consideration.

I’m curious about the details of your experience considering your issues with debugging. Personally, I’ve found the debugging aspect to be much more pleasant with FP-style systems.

1

u/Zardotab May 06 '19 edited May 07 '19

depends on the company, the team composition, the codebase, and the languages

Indeed. The success often depends on how you use & manage the tool more than the tool itself.

I just can't find examples relevant to domains and projects that I see. I'm not predicting the weather 8 days ahead or starting the Next Great Dotcom, I'm merely tracking the workflow of widget processing for Drab Company Inc. Unglamorous, but necessary. (Don't tell them I said that.)

When I see relevant examples, then I can better comment on debugging. If I use examples that I conjured up by myself, others say "you are doing it wrong", but don't give me viable alternatives. Their reworked examples assume domain patterns that don't exist in practice, leading me to suspect that FP requires too much "regularity" in designs. Some domains have more regularity than others. For example, the laws of physics or an existing standard is not going to change much such that most new features are additions rather than changes of what already exists. In my domain, the "rules" usually come from the whims of managers, owners, lawmakers, and/or marketers.

1

u/ScientificBeastMode May 07 '19 edited May 07 '19

You bring up some good points. If you don't have the authority or freedom to make changes to your work processes or tool-set, then switching to a new programming paradigm is going to be difficult, and probably won't offer as many benefits.

A lot of the problems that FP addresses are essentially top-level concerns (e.g. test coverage, test quality, error frequency, cost of refactoring, etc.), so migrating to a functional language (or design paradigm) is more relevant to a senior engineer or manager. One rogue developer opting to turn all of their code into nested functions is probably not going to see many of the systemic benefits that they might see if FP design was implemented across large sections of the codebase.

So if the question is, "Why should I, some average developer at a random company, switch to FP?", I could come up with a few reasons, but it's a hard sell. If you aren't familiar with it, the learning curve is tough. It's harder than switching between, say, C# and Java, which is basically learning different implementations of the same core concepts. Switching from C# to Haskell involves completely rethinking the way data ought to flow through an application. For me it felt like I was learning calculus for the first time.

But I guarantee you will become a better programmer if you learn FP (or heck, any new, unfamiliar paradigm). Just my hot take...

Edit: I have come across some examples of companies using FP to solve real-world, mundane technical problems. And often the results are rather boring on the surface. Usually it means something like having literally zero runtime errors for several years. Or implementing concurrent computation across an entire application without having to think to much about it. Or how Facebook managed to permanently squash a persistent bug with their messenger app by migrating portions of their code to ReasonML, a semi-functional language. Plenty of examples out there, and many of them are just solutions to ordinary business problems.

1

u/Zardotab May 06 '19

Programming is a dead-end career; I wouldn't expect anyone to exert too much energy trying to master everything because it doesn't pay on average. For that reason, K.I.S.S. should apply above all else. For whatever reason, ageism, burnout, RSI, etc. programming salary plateaus and jobs get more difficult to find. I know there are exceptions, but one cannot know if they are the exception. The industry "hates" oldbies. I'm just messenger, so don't "shoot" me with negative ratings.

1

u/devraj7 May 05 '19

Did it ever occur to you the bad OOP code you're seeing has a lot more to do with the quality of the programmers who wrote it than OOP per se?

7

u/lelanthran May 05 '19

I'd rather work with programmers following these principles

...

Did it ever occur to you the bad OOP code you're seeing has a lot more to do with the quality of the programmers who wrote it than OOP per se?

He kinda literally said so.

1

u/CODESIGN2 May 05 '19

They literally said so

5

u/editor_of_the_beast May 05 '19

Idk. The best OO code to me looks like a poor manual implementation of functional code.

1

u/ScientificBeastMode May 06 '19

This is basically what I’ve seen as well. It’s really interesting how my code quality has improved in traditionally OOP languages after spending a little time in FP land. It’s like suddenly I understand what classes can really do if you design them well...

But any engineer in any field will tell you that human error is the enemy of all good things in the world. Trusting every programmer to know good OOP design, and also execute it, is simply bound to fail.

4

u/glacialthinker May 05 '19

That's kinda what I'm saying, right? Are people only reading my first paragraph?

8

u/[deleted] May 05 '19

I think the problem is that your second paragraph doesn't logically follow from the first.

In the first paragraph says that you hate OOP because of the poor quality of code that results. But in the second paragraph, you say that better programming techniques lead to higher quality OOP code.

These are contradictory statements.

3

u/CODESIGN2 May 05 '19

I think they said that better techniques barring heavy encapsulation except around service boundaries make higher quality code regardless of paradigm.

It's not contradictory unless you have your encapsulation == oop goggles on. You can encapsulate in a number of ways starting from the humble function for behavior and data (with constant / idempotent being the default without static or other clever language features or libraries being used).

def pi():
    return 0 + 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899

def to_radians(degrees):
    return degrees * (pi / 180)

def to_degrees(radians):
    return radians * (180 / pi)

That is to say without knowing the formula you could encapsulate the algorithm and pass by name, or simply call by name (more primitive, but passing by name usually requires functions to become object or object-like)

1

u/[deleted] May 05 '19

Well yeah, but that isn't an argument for why OOP tends to produce poor quality code. Good coding practices are practically universal.

1

u/CODESIGN2 May 06 '19

Put another way (as someone that likes OOP but doesn't put it on a pedestal)

OOP gives you the scissors, you choose to run with them instead of cutting things with them. Holster your scissors if you plan on running.

0

u/Sum1FromSomewhere May 06 '19

Give the guy a break. What more do you expect from someone who upvotes his own comments from pseudo accounts?

1

u/flukus May 05 '19

It's not, it's the one's following "good" OOP principles like encapsulation that suck.

1

u/Zardotab May 06 '19

Someone once said, "Judge a paradigm/framework by how idiots use it, not geniuses." Or at least average.

-1

u/Sum1FromSomewhere May 05 '19

It's like saying "I hate the English language because in the few books I've read, the authors aren't good at structuring their stories."

3

u/glacialthinker May 05 '19

Completely failed analogy. Natural language doesn't impose much on structure. It's literary techniques like poetic form, essays, letters... these are what impose structure, and this is more like the effects of paradigm or orientation.

-7

u/scientz May 05 '19

It sounds like you are doing it wrong. OOP is a way of thinking and modeling, not organizing or writing the code. You use the patterns and tricks where it makes sense, not because it was laid out in a book etc.

8

u/glacialthinker May 05 '19

I'm not doing it at all, generally. I'm talking about when I work with an OOP codebase or a subsystem which is written by someone who learned with Java and design patterns (too common these days).

3

u/Jump-Zero May 05 '19

I agree with you. I dont blame OOP itself, I blame C++ for being so verbose and influencing Java/C# which are verbose as hell too. Many design patterns can be accomplished with much tighter code using more modern languages.

-2

u/pron98 May 05 '19 edited May 05 '19

10% of the code being relevant to the problem

I would challenge that number. People who tend to bring this up also tend to greatly exaggerate differences in LOC between different languages/styles. While boilerplate may end up taking up a non-negligible portion of a small program, it is not all that much in large programs (and those are the ones that matter, because small programs are easy to understand, anyway). When we look at large programs we see a similar number of LOC regardless of language/style (of course when comparing high-level languages). You may see a 1.2x difference, or maybe 1.5x difference in some cases, but you don't see a 3x or a 5x difference, let alone 10x.

My hypothesis for why some people tend to so grossly overestimate boilerplate or other kinds of "accidental complexity" in current high-level languages is simply because however much there is, they find it annoying, and when we do an annoying task we exaggerate its scope.

1

u/glacialthinker May 06 '19

Your reply made me reflect a bit on why I said 10%. It seems I have three codebases in mind which are fuel for this: OO gameplay code from almost 20 years ago, most of the 1mil lines of CryEngine, and the Oculus SDK. I guess these scarred me. However, these are also the codebases heaviest on object orientation and design patterns which I've worked with (and CryEngine isn't all that OO... just enough to kludge it up, though several coworkers did their best to add even more "good OO practices" so that added to my frustration).

The reality is that refactoring could slim the code tremendously in all of these cases, though it would likely be more of a rewrite because of the amount of abstractions involved -- and this is part of my gripe. Abstractions should make this easier. In practice, these out of control design-patterns and encapsulation-heavy codebases are rigid and unless interfaces are very carefully designed, they also need to change -- often many layers worth. It's like "Oh I forgot the stuffing in the chicken in the turducken -- let's cut through all those layers and try to fix this and sew it all up."

Anyway, due to your reply I was thinking "yeah, I'm probably exaggerating", but no I can't say I was. And we do have examples of codebases shrinking by 5-10x when they are rewritten. It doesn't have to be a language thing, but my issue is that object-oriented style seems prone to getting out of control. That's just been my experience. Even classic procedural C-style code is just simpler, with a higher density of code relevant to the problem rather than filled with unnecessary (or even self-defeating) abstractions.

1

u/pron98 May 06 '19 edited May 06 '19

And we do have examples of codebases shrinking by 5-10x when they are rewritten.

That's true. The reason is that code is written organically. You're not sure what exactly you'll need, you don't fully understand the problem, etc..

It doesn't have to be a language thing, but my issue is that object-oriented style seems prone to getting out of control.

I have a feeling, though no data to support it, that the more clever the language, the more distracting it is from the domain, drawing programmers -- especially younger programmers -- to use clever features. Of course, it may have its advantages, but it could also lead to YAGNI. The C++ codebase I'm working on now (HotSpot) is over 25 years old, but I don't see this problem there at all. Neither did I see it in the other codebases I personally worked on, but I have usually worked on codebases written by very experienced developers. HotSpot, in particular, is heavily maintained and constantly refactored; just the other day someone deleted many thousands of lines in a refactor. We try to write the simplest code possible, and only go back and add abstractions if we see that a piece of code requires constant changes to support new features. But when that happens -- and it happens often, just not everywhere -- we appreciate that we're not using C. I agree there is a tension between using a language with more powerful abstractions, and a desire to use that power even when unnecessary, but I also hear many complaints about the opposite problem, where codebases written in very unpowered languages (e.g. Go) that the lack of abstractions also leads to a lot of waste.

0

u/[deleted] May 05 '19

[deleted]

5

u/glacialthinker May 05 '19

Good programmers don't over-use design patterns. Programmers relying on design patterns for all code are bad. ...This kind of idea.

Design patterns were not intended to be recipes, but that's too often what happens and horrible OOP codebases are a soup of design-pattern implementations.

The principles in the subject-article are much more relevant to writing good (writable, readable, maintainable, extensible) code. Design patterns are frequently recurring problem+solution ideas mostly related to implementation details. They're fine if used properly, but they don't take the place of good programming practices.

2

u/dys_bigwig May 06 '19 edited May 06 '19

I think good programmerstm are able to see that design patterns are a result of missing language features, and as a result stop using them if/when the language designers add these features. For the most part in this post I'm assuming that the person may be inheriting some code that's already in language A, and language A doesn't have said feature/s. Otherwise, a goodtm programmer wouldn't have chosen to write said program in that language.

After going back and reading some java-oriented design pattern books that I struggled to understand initially, I found I was able to skip most of the sections because I'd realise quite quickly "Oh, so, that's a kludge you can use to compensate for a lack of first-class functions in a language that doesn't have them. Good to know!". Same goes for a lack of decent module capabilities and singletons.

I genuinely believe that it's important -- with the preceding ideas in mind -- to explain why this-and-that design pattern would be used. Not because it's a good idea to use them for the sake of it, and not because it's even good design in general, but because it's a way of compensating for a lack of a certain feature/features in a language.

They're not pretty, they're not elegant, and they're hardly ever as easy to follow as the feature they're trying to imitate. That's not the fault of the person using them though, it's the fault of the language. Well, unless that person is choosing to write a program in a language that was not designed to write that sort of program. In that case the onus is on the programmer for picking the wrong tool for the job.

5

u/Scybur May 05 '19

Nice break down but the usage of “Btw“ every second paragraph is weird.

1

u/andre_2007 May 06 '19

Nice read. Maybe you could also emphasize, although most problems can be solved with OOP, there are cases where other development paradigms fits better and vise versa. For example, the D Programming Language provides multiple development paradigms like OOP, FP, meta programming,... and the developer can choose which paradigm fits best or even combine them to solve a problem.

2

u/javinpaul May 06 '19

Thanks adre_2007, I haven't looked at the D but Scala is the closest one where I have seen the best of both OOP and FP, and it does help.

1

u/andre_2007 May 06 '19

The inventor of Scala was last year guest speaker at the D conference in Berlin. He gave a quite nice presentation. You may come back in future and have a look D, it combines both paradigms and multiple others very well.

3

u/CODESIGN2 May 05 '19

I like the part about coding for interfaces and not implementations. It's harder to do than it sounds. Many interfaces suck because of exactly this. You use push and pop and all of a sudden the backing uses LILO semantics in it's core language, people need to fight the language and their idea-set gets narrowed.

I have to add that it is becoming more and more rare to see people pushing this though.

Imagine you have an average of 4-5 tickets per-day. There is no way those are going to be designed well.

At work we have a thing for storing unstructured data that nobody understands well because it was never documented. As a result everyone hates it. I recently defined a new interface to get at the underlying data and I can see what the author intended. It was quite naive, but also rather beautiful. Any object would extend an interface to be able to store form_data (I think their first mistake, brought about by using ORM). From within that you'd be able to access any object's FormData using a common shared property (weak encapsulation, duck-typing madness).

Put in one or more Interface definitions, they could have added a get_formdata method to a IReadsFormData attribute (where it reads from doesn't matter), and had a set_formdata method on a IWritesFormData methods and it wouldn't matter which property, or even if a property stored a link to all the entries an object could ever have. In-fact it would have freed them entirely from this single table polymorphism BS I keep seeing shat over code-bases.

PS: Anyone that loves data-level polymorphism

  • your address space is incapable of storing that many records. The more types you add, the less each can store.

  • why couple storage to business logic? If in future you decided to migrate to a graph store so you can gain insights to how data relates, how will you do that if you pin this directly to some shitty ORM backing? A lot of hard work

  • How will you manage separation of concerns, neigh separation of domains when the systems naturally mature?

5

u/AlphaDeveloperZA May 05 '19

That's SOLID advice.

-9

u/shevy-ruby May 05 '19

Not really.

Why not?

Because it attempts to tackle different philosophies/usage of/in OOP into "this is the only true OOP way and everything else must be worse". And that is totally rubbish.

Let's use an oft-used Alan Kay quote here:

https://www.quora.com/Why-did-Alan-Kay-dislike-Java

Even with an explanation (though that was not what he may have said origianlly, but it is a good summary nonetheless IMO).

What amazes me is ... people love to critisize Agile. Fair enough, the word itself is a dead-giveaway for marketing. But then they happily use Java and don't understand how there could be anything other than Java for OOP.

And why is DRY even there? Why would this be connected in any way to OOP and nowhere else?

It's logical that, if you can AVOID repeating yourself, that's good. So why is that even mentioned.

It reminds me of other loop-repeated statements such as "use the right tool for the job" (but never specify what this really means) or "learn all the languages" (yeah right because people have an infinite amount of time) or "you will only understand concepts if you use a language which has this concept" (yeah right ... as if any idea is tied to an IMPLEMENTATION ... or does your brain have to ask for some permissions before it can have an idea?).

hackernoon.com is medium.com right? So no surprise ... I dunno why but they always want visitors to log in; probably because the clickety-click leads to monetary flow. Otherwise why are people even using that terrible format for posting their ideas about any subject?

9

u/riotvaninho May 05 '19

I think the joke went a bit over your head buddy

6

u/scientz May 05 '19

"a bit" lol.

5

u/shAdOwArt May 05 '19
  1. Applies equally to all programing paradigms.

  2. Applies equally to all programing paradigms.

  3. Applies equally to all programing paradigms.

  4. Applies equally to all programing paradigms.

  5. Applies equally to all programing paradigms.

  6. How to avoid bad designs that are only possible in OO.

  7. Applies equally to all programing paradigms.

  8. Applies equally to all programing paradigms.

  9. Applies equally to all programing paradigms.

  10. Applies equally to all programing paradigms.

2

u/CODESIGN2 May 05 '19

You can call a function from within another function, then you can compose without OO. What were you thinking? Inheritance could be a specific form of composition if you think about it, you just call the parent function within and set it to a local called parent. You could probably do this using Macro's but then you would be abandoning a lot of engineering

1

u/Zardotab May 06 '19 edited May 06 '19

If you are coding in Java then follow the principle of making variable and methods private by default

I disagree, that creates a lot of verbosity, which slows reading and creates more room for typos. Wait until there is an actual reason or a high likelihood of need. Other languages allow one to switch to accessors under the hood without changing caller code by making a method versus property an interface issue or one in the same (swappable). For example, in "a=x.foo;", "foo" can be a method or attribute. If you start out with "naked" attributes and later need to wrap it, you usually can without reworking code that references "foo". You don't have to "pre-bloat" your code with accessors to achieve that. Java is flawed this way in my opinion, and I hope they fix it. Pre-wrapping everything "just in case" is a bad practice.

The rest of the examples rely too much on shapes, which don't make good examples because in the real world, the subject matter changes more frequently. The rules of geometry are too static to be a good test. I realize they are just training examples, but I've seen people mis-apply lessons learned from shapes into the real world.

And be very careful about splitting domain things into "types". Often that's too blunt of a model. A buffet of features assigned to objects is more flexible. It's similar to the article's Rule 6: "Favor Composition over Inheritance." However, OOP is lousy at set theory in my opinion in order to manage the features as sets. I'd like to see relational modelling extended into code structuring: table oriented programming. OOP is not powerful enough without reinventing a database in it.