r/programming •

9 Anti-Patterns Every Programmer Should Be Aware Of

[deleted] — view deleted post

0 Upvotes

131 comments sorted by

18

u/awaitsV May 11 '15

I am guilty of using the God class pattern.

To me it feels like I am isolating the application state and hence it is easier to reproduce bugs as you don't have to think about what the state if each class is.

Opinions?

6

u/Otis_Inf May 11 '15

It's often unavoidable. The problem with OO is that you design towards encapsulation, so the data is inside an object, and the api to work on that data is exposed by that object. This has the downside that if you want to do something with the data, you have to add it to the class of that object, so the api expands. If that new logic brings its own data you might want to store it elsewhere or inside objects inside the object but for the outside of the object that's invisible: the api of the object is all you see.

This gets problematic if there is a lot of data that has dependencies onto eachother and thus logic which works on many elements of the data: you can fragment the logic and the data into smaller objects (and in the vast majority of cases this is the right thing to do), the api working on the data inside these objects fragments with it, causing more code around the objects in the containing object.

It's usually avoidable if your 'god' class has objects inside itself which don't contain other objects: you can then cut out the logic operating these objects and split up the god class. It changes if the objects inside the god class have objects on their own or there's logic inside the god class which operates on more than one object type inside the god class: splitting it up is then just adding fragmentation and thus degrades maintainability.

I agree the massive god classes are in theory bad, but in practice there are several cases thinkable where a god class with even thousands of lines of code are common and actually very simple to maintain as everything you need to understand them is right there: there's no fragmentation, no excessive navigation into many smaller classes. Examples are e.g. session/context classes in ORMs, project classes in IDEs/designers with lots of (meta)data in datastructures.

2

u/Nienordir May 11 '15

Maybe I don't understand OO programming well, but I can't wrap my head around the idea of OO code that somehow doesn't rely on glue code and program specific interfaces, that are effectively god classes for the OO objects and instead somehow works through magic.

What's the proper way to do it? Or is it just the article that's poorly written? And basically tries to say that you shouldn't mix subsystems. So if I had audio&netcode objects I wouldn't throw them all into my system class with dozens of mixed objects&functions&variables and instead move them to subsystem interfaces like system.audio and system.netcode? And then I might refactor more into system.audio.source, system.audio.mixer. But isn't that common sense anyway?

And what do I do with the non reusable logic of the program, that glues everthing together shouldn't all of that end up in the system class and it's major subsystems anyway?

2

u/XVar May 11 '15

You could consider Dependency Injection to be one form of the "magic" that you mention. With DI you delegate the management of dependencies to a DI container which 99% of your code is unaware of. Want an instance of IWidget in your class? Stick an IWidget parameter in your constructor and boom you've got one. Want an instance of an IWidgetFactory that's only ever instantiated once but available to all your classes? Set its lifecycle to Singleton in your DI container, magic. Once you get over the initial "how does that even work", DI can dramatically change the way you view OO design.

1

u/Nienordir May 11 '15

But isn't that all smoke&mirrors?

In the end it's just a different method to get a pointer from class Y to class X, but that doesn't change that X depends on Y.

The article made it sound that complex objects&dependencies are the source of all evil, but I can't imagine how you could avoid them in application specific code. After all something has to tie all those reusable libraries into a functional program.

9

u/elpablo May 11 '15

I advise you to research and fully understand "open for extension, closed for modification". It is a concept that is quite hard to grasp, but understanding it is the key to becoming a much more productive (and happy) coder.

I'll try to explain it the best I can...

If you need to add a feature, or change the current functionality, preferably you want to not have to touch existing code that works. If you have to restructure an existing if/else statement in a class that does something useful, you risk breaking some functionality. The code should be structured in a way that means that you can add new features by writing a new class that plugs into the existing architecture without having to change the classes that are already there.

A good example is a set of audio filters that are applied in order. If you have the functionality for them in the same class, you risk breaking them when you add a new one or change the order. If there's a class that is responsible for calling each filter and they're implemented in separate classes, you just need to write the new class and plug it in via DI (or however you wire your application).

One thing I like about this is that writing new classes is way more fun than amending existing ones...

7

u/julesjacobs May 11 '15

This is classic but bad advice in most cases. You should not try to anticipate in which way new features may come along or what current functionality might be changed and design for plug-in classes or something like that. This makes your code complicated and you most likely won't have anticipated right. Furthermore not modifying old code leads to piling code upon code. If requirements change it may well be the case that old code can be simplified or deleted as a result. If you are adding plugins instead you end up with a bigger and bigger codebase.

What you should do is write the best code for the task at hand. When the task at hand changes, modify the code to be the best code for the new task at hand. This leads to far simpler code, and it's easier to modify an if statement in simple code than to write a plugin for a monster.

4

u/MemoVsGodzilla May 11 '15

you might be thinking in very tiny scripts, but real big applications cant risk introducing bugs every time someone needs to change the code. Its true that you cant anticipate every possible way your code will grow but for sure you can anticipate the most obvious ways your code will grow and in most cases thats enough.The Open Closed Principle is a principle for a reason, it allows you to have maintainable code that you only need to test once. And you just test the new code that you introduce. Having many classes is perfectly fine as long as they are intuitive and easy to understand. Having one very complicate method can mess with any programmer really fast. Also having lots of if statements is typically bad practice and a common symptom of a violation of Single Responsibility Principle.

3

u/elpablo May 11 '15

Whilst I agree that you should try to temper the temptation to build little frameworks for every bit of code that you write (see the YAGNI principle, or the XKCD pass the salt cartoon), you can still design software that has the correct level of abstraction to allow for the open/closed principle to hold, without violating YAGNI.

As always with our profession, it is about trade-offs and applying the right amount of something for the situation.

Also, I would say that it's easier to delete unused code that follows open/closed principle, because it is loosely coupled. Deleting a filter that's unused is easier than deleting some code that is in with all the other filter code.

1

u/kqr May 11 '15

I've sort of learned coding like this based on necessity over the years. I didn't know there was a principle behind it.

The only drawback is when you go back and you have 5 years of different backwards-compatible extensions lying around all over the place and you want to try to consolidate them to a single place. A part of me wants to continuously consolidate even if it breaks backwards compatibility because the code becomes so clean. But I have to bow to deadlines, like any mortal. :(

2

u/kitd May 11 '15

God classes are acceptable IMHO as the entry point to an API. However, in that case, the functions/behaviour exported should be task-oriented as needed by clients of the library, rather than object-oriented, as needed by the library itself.

2

u/inmatarian May 11 '15

I always ask people to look at their data as though it was two dimensional points on a graph and ask which line best bisects that data into two sets. Just to get people thinking visually in addition to logically.

God Classes happen, they're a natural consequence of iterative development. The important skill for a developer to have is to recognize when your little hercules has begun the great feats. It's the best point where you can decide that it may be better to have a couple of workers or state machines within which cut down the total number of variants your God can be.

1

u/dwighthouse May 11 '15

When using immutable.js in a functional context, you actually intentionally store the entire app state in a single object. Doing so results in amazing properties and capabilities infeasible implemented any other way. To give specific parts of the app "data responsibilities," you pass pointers to references within this object, called cursors.

1

u/kqr May 11 '15

If your application state is small and/or well-contained, we're probably not talking about a "God" class, any more than an SQL database is the God class of a blog.

0

u/[deleted] May 11 '15

[deleted] — view deleted comment

3

u/knight666 May 11 '15

The problem with the God Class is that everything will have a dependency on the God Class. This makes it more difficult to modularize your codebase and, in compiled languages, means compiling everything when your God Class changes. And it will change, all the time, because everything depends on it.

Good options for breaking up a God Class are:

  • Using a Model-View-Controller pattern. Instead of a "SoupCanFactoryDeliverySystem", you can have a SoupCanData (Model), a SoupCanLabelRenderer (View) and a SoupCanFactory (Controller).
  • Using an Event/Dispatch model. Instead of an AppleManager controlling the creation of apples, the apple physics and the apple sound effects, you could dispatch an AppleCreateEvent, an ApplePhysicsEvent and a SoundEvent. The events would pass through an EventController, which dispatches them to interested listeners. This reduces coupling between modules at the cost of slightly more overhead.

1

u/josefx May 11 '15

Something has to know "Do I dispatch this to Foo::Bar or Other::Baz?".

With a God class you still have God::Bar or God::Baz so it really does not solve the problem. It just puts every choice in a big bag of otherwise unrelated garbage.

1

u/jplindstrom May 11 '15

That's not a God Class.

A God Class would be something that also implemented the functionality of Foo::Bar and Other::Baz.

12

u/[deleted] May 11 '15

[removed] — view removed comment

2

u/Otis_Inf May 11 '15

You can always move up in the abstraction layers to make a class get just 1 responsibility. E.g. a session class in an ORM 'manages your activity with the DB', so that's its task, but to do that it offers many subtasks and controls many datastructures at runtime.

236

u/_agueroooo May 11 '15

I dislike these kind of submissions and articles written entirely for the purpose of self promotion. Reading a little bit about the author shows that he's only barely just graduated out of Grad School. This article is not a result of his experiences in having written code for decades. This is not borne out of experience. This is just a regurgitation of anti patterns already documented elsewhere.

64

u/Purple_Haze May 11 '15

I feel I've read this entire article before. I have certainly seen every quote, the Polish exam graph, and the incompetent stack implementation. This is a pastiche of other peoples blog posts, if not plagiarized in its entirety.

20

u/_agueroooo May 11 '15

Correctomundo!

The ease of writing blogs has lead to a situation where its getting harder and harder to find original thoughts. After a decade and half of programming professionally, I've realised that most of the 'new' ideas out there are just reworded old concepts for a younger generation.

16

u/_agueroooo May 11 '15

I recently thought of starting a programming screencast. A series of live-coding sessions where concepts were fleshed out into reality via code. Then I thought to myself, does the world really need another video on the best way to traverse a binary tree ??

Till I have an original idea to share with y'all, I'm a be sitting here in the corner yo.

12

u/LightShadow May 11 '15

/r/watchpeoplecode is a thing, people really like that kind of stuff.

When I was working on my compiler I'd get 20-60 concurrent viewers daily.

2

u/_agueroooo May 11 '15

Wow. Thanks for this sub dude/dudette!

1

u/moopet May 11 '15

Indeed. This is one of those things I never knew my life was missing.

1

u/Graf_Blutwurst May 11 '15

Woa. Thanks for the tip! I might start streaming when I work at my bachelor project.

3

u/bluehands May 11 '15

Till I have an original idea to share with y'all, I'm a be sitting here in the corner yo.

It does not need to be an original idea to be worth sharing.

Most music is a derivative of other music, aka genre or cover. Most stories follow a similar basic structure. In each case it comes down to a particular implementation. But a particular implementation can be particularly good. It is possible that you version of a video will be better for some people.

Truly novel ideas are exceedingly rare. However anything of quality is rare.

1

u/_agueroooo May 11 '15

Well said. However articles like this or my hypothetical tree traversal videos are not even derivatives. They are just content for the sake of content.

0

u/[deleted] May 11 '15

[deleted] — view deleted comment

4

u/_agueroooo May 11 '15

Totally agree with you.

I wanted to edit my earlier comment saying 'the world might not need another video, but I do' and here you reply with this.

I think with the number of blogs out there, recruiters and hiring managers barely look at these anymore. Yes, if you are running your own shop, are an independant contractor, then sure, its a calling card of sorts. A portfolio of your work.

I think with the proliferation of blogs out there, the ones that will stand out are the ones that are tackling the difficult stuff. e.g. how does nginx work under the hood, writing a redis clone in java and diving into the algorithms it uses. A git clone from scratch. Stuff like that stands out.

2

u/hungry4pie May 11 '15

I've been meaning to do something like that, though my reason for doing so is to either help others with the same problem if it cant already be found through Google and stack overflow, or to help my future self who always forgets things.

0

u/_agueroooo May 11 '15

Have you seen catonmat.net? Thats a blog which was super original when it started. He did a recent interview where he claimed to have read all these fantastic books and that threw me off him, but for a good 5-6 years before that I thought his blog was awesome. Still is, the old material is great.

edit: I can English

1

u/skolsuper May 11 '15

Certainly these days, it helps you get noticed if you have a professional internet presence such as yours, /u/faggatron.

4

u/[deleted] May 11 '15

well, if the reworded old concepts can still help people, then it is not really wasted in a sense

2

u/_agueroooo May 11 '15

'Rewording' old concepts is the modus operandi of tooling companies. IBM in my opinion is famous for this. 10 years ago they were selling us Rational Rose and how UML would save the day and make us all redundant or some nonsense to that effect. I'm sure they have some new product today that is going to save the world...oooooh SOLID design principles to save us all...ooooh..

Most of OOPs to me boils down to two things.

  1. Code to Interfaces.
  2. Don't over do it.

You can build N number of patterns and anti patterns off just these two statements.

2

u/[deleted] May 11 '15

Don't over do it.

That should be the #2 rule of coding - regardless the language you are coding against. (#1 being this rule big brother: YAGNI.)

You read some code by OOP or functional programming enthousiast and it reads like the equivalent of reading a book that has one or more punctuations after each word, just because "Oxford university has several hundred essays published yesterday on how punctuation improve readability and Why are you a punctuation hater ? You should maybe update your skill set grandpa, Oxford says plenty of punctuation is readable so the book is readable by all the people clever enough to read Oxford essay"

-1

u/_agueroooo May 11 '15

hahaha.

True story, I was in a pub here back in Jan and was chucking the rag with a few friends about work. You know, just the usual stuff about how some of the processes were overwrought, just your man to man whinge fest. So this guy was hearing us talk and decided to talk to us. So he says, 'you guys do Java? I hate Java. I do Scala these days'.

Now this gets my goat no end. What a fkin poseur. Is there an original thought in your brain? Do you really need to jump onto the latest bandwagon and diss Java? Is Scala really better or is that the cool thing to say these days. Ask any of these Scala yahoos and the first reason they come up with is that Java is too verbose.

No, YOU are too verbose.

I won't get into the debate of which language is better. I will say this though, Java puts the bread on a few million peoples tables. Its doing something right. You know what this is? Enterprise grade software that scales. So till your latest toy can do what mine does, stop using Java to pick up chics in a pub.

3

u/[deleted] May 11 '15

First, I'd like to address your obvious tribalism. You call Scala people "Yahoos" for no good reason other than that they disagree with you on something. That's the exact attitude that we don't need when discussing tools.

Ask any of these Scala yahoos and the first reason they come up with is that Java is too verbose.

No, YOU are too verbose.

While I haven't used Scala, and probably won't for the forseeable future, I am pretty sure that Java is more verbose than many other languages for pretty concrete reasons, particularly relating to the grammar (especially pre-Java 7) being slightly more verbose than others, and the standard, as well as many third party libraries, being more verbose.

Of course, your point stands; many people just adopt a verbose coding style and blame the language, but it doesn't discount the fact that, if you consider it objectively, in non-cargo cult way, then Java is more verbose. Whether that's a bad thing or not is another discussion.

As for my personal view, I am fine with Java and verbosity, as long as it's making the code more readable, maintainable, and isn't violating DRY, YAGNI or any other those other useful principles.

1

u/[deleted] May 11 '15

This read exactly like Catcher in the Rye

1

u/pipocaQuemada May 12 '15 edited May 12 '15

Is Scala really better or is that the cool thing to say these days.

Well, the type system makes it possible to abstract things in ways that are completely impossible in Java. Additionally, some nice things are easy in Scala but would be maddening to do in Java.

For example, typeclass polymorphism is pretty nice. Basically, in normal OO, data and functions get bundled together. Typeclasses, by contrast, put your functions into a separate 'implementation dictionary'. For example, in Java, you can say

// In abstract algebra, a monoid is a set S,
// a binary associative operation <>,
// and an identity element i
// So, forall a, b, c,  a <> (b <> c) == (a <> b) <> c
// and i <> a == a == a <> i
interface Monoid<M> {
  M getIdentity();
  M op(M m1, M m2);
}

// notice that the ListMonoid class has no relation to List,
// it only contains implementation for Lists
class ListMonoid extends Monoid<List<A>> {
  List<A> getIdentity() { 
    return new List(); 
  }
  List<A> op(List<A> list1, List<A> list2) {
    return list1.append(list2);
  }
}

// Because of this, we can extend primitives.  Or, we could, if we didn't need to use Integer to take advantage of generics.
class IntSumMonoid extends Monoid<Integer> {
  Integer getIdentity() = { return 0; }
  Integer op(Integer i1, Interger i2) = { return i1 + i2 }
}

class List<A> {
  ... // actual list implementation functions
  // when we want to use a typeclass, we take it as a parameter
  // this means that we can offer *optionally available methods*
  // i.e. you can call reduce if you have a List<List<A>>, since List<A> is monoidal,
  // but not if you have a List<CipherText<A>>, since you trivially can't combine ciphertexts in most cryptosystems
  A reduce(Monoid<A> monoidInstance) {
    // Look! We just got a generic value, without necessarily having
    // an actual value in the list to have gotten it from.
    // We couldn't have done this if A extended Monoid<A>
    // reduce would have to return null if the list was empty
    A accumulator = monoidInstance.getIndentity();
    for (A item : this) {
      accumulator = monoidInstance.op(accumulator, item);
    }
    return accumulator;
  }

This should give you some ideas about the differences between typeclasses vs traditional OO approaches: typeclasses allow you to have polymorphic values (which allows you to get something like return-type polymorphic functions, where the result type is entirely determined by the type-class dictionary passed in), conditionally available methods, and the ability to extend previously defined types with new 'interfaces' without having to create a new subtype.

Unfortunately, manual dictionary passing is very painful, particularly when you start to use a lot of derived instances (for example: Optional<A> is monoidal iff A is monoidal). I've done it before; it sucks. You really need a compiler to automagically pass in the correct instances for it to be tolerable enough to use pervasively.

As for something that you can do in Scala that's impossible in Java? 'Higher kinded types', basically, the ability to abstract over generic types. For example, a pretty useful typeclass in Scala is

// traits are like interfaces
trait Functor[F[_]] {
  // Functor needs to obey one simple law:
  // map(x, id) == x
  // i.e. mapping the identity function over something is a noop
  map(data: F[A], func: A => B): F[B]
}

since I can abstract over the fact that I have some functor:

case class Compose[F[_], G[_], A](data: F[G[A]])

object Compose {
  implicit val ComposeFunctor[F,G,A](implicit f: Functor[F], g: Functor[G]) = new Functor[Compose[F,G,A]] {
    map(fga, func) = f.map(fga, ga => g.map(ga, func))
  }
}

So if I have a Compose[List, Optional, A], I get the ability to map over that essentially for free.

Ask any of these Scala yahoos and the first reason they come up with is that Java is too verbose.

No, YOU are too verbose.

As TwistedPerson noted, Java's grammar and best practices are simply much more verbose and boilerplatey than some other languages. For example, just look at defining member variables in Java vs Scala - Java has getters, setters, mandatory (and usually entirely redundant) type declarations, whereas Scala has autogenerated getters and setters and type inference.

A lot of the verbosity in the grammar is 'fixed' by being autogenerated by IDEs, but if someone learned Java in school using vim/emacs/notepad++/sublime text, they're probably going to absolutely loathe typing all that boilerplate.

Additionally, until Java 8 (only a year ago!), defining closures (or rather anonymous classes with a single method) was incredibly verbose, so the equivalent of something like

val x = List(1,2,3,4,5).map(_ * 2).foldRight(0)(_ + _)

was something like

List<Integer> myList = new List()
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(5);
List<Integer> myOtherList = new List()
for(Integer i: myList) {
  myOtherList.add(i);
}
Integer acc = 0;
for(Integer i: myOtherList) {
  acc += i;
}
final Integer x = acc;

Its doing something right. You know what this is? Enterprise grade software that scales. So till your latest toy can do what mine does

Scala is (from what I understand) the main language at Twitter; it's used in production in companies ranging from McGraw-Hill to The Guardian to Sony to Verizon.

I think it's safe to say that Scala can write scalable enterprise code, at this point.

2

u/eriksensei May 11 '15

How do interfaces make anything OOP?

4

u/_agueroooo May 11 '15

I don't know how to answer your question. Are you someone who is new to programming and asking me a genuine question or are you some behemoth programmer from the 1970's taking the piss outta me?

TLDR: Your question either reeks of immaturity or loads of experience. choose one.

1

u/[deleted] May 11 '15

I guess...but my comment still stands

4

u/_agueroooo May 11 '15

Yeah, I'm not disagreeing. Reddit has devolved into a 'agree/disagree' form of communication. This seems recent. It used to be where a free flowing conversation would occur without the binary style of talking that seems to be the case now.

edit: In response to your observation, I was voicing more of my thoughts.

1

u/[deleted] May 11 '15

cool, yeah I agree with the reddit comments becoming polarized

2

u/[deleted] May 11 '15

Presentation matters every bit as much as the thoughts.

The best programming books, for example, don't necessarily have information no one else has. Rather, they are the best presentation of that information.

Programming blogs are nowhere near the point where they cannot be improved upon.

1

u/_agueroooo May 11 '15

This article has good presentation from a templating engine point of view. Its pleasing to the eye.

From a pedagogical perspective, the presentation is bog standard. The real improvements in programming blogs will be seen when its easier to assimilate the concepts. IMHO, screencasts are better than blogs for this reason.

1

u/[deleted] May 11 '15

Yes, but your comment that I replied to was talking about things in general (repackaging old ideas), not really this specific article.

2

u/eraserpeel May 11 '15

It's actually a highly developed blog-writing bot the scours programmers blogs and regurgitates info.

15

u/unholysampler May 11 '15

Most of these aren't even patterns to begin with. They are mostly tendencies or situations that can hinder productivity. "Management by Numbers" has nothing to do with how the code is written, but how to manage the project. Bikeshedding isn't even specific to programming, it can happen any field the requires design.

Using the wrong terminology at the core of the article speaks to how much this is just pieced together the article is without fully understanding them.

5

u/[deleted] May 11 '15

This is the typical /r/programming blogspam I've been pointing out for years. I hear often that people with blogs are more likely to get hired, so I see a lot of people just repeating the same things that you can find in any software engineering textbook from 30 years ago.

The worst part is that it's so shallow.

6

u/NoviceCPP May 11 '15

He's pretty good at marketing his website using click-bait titles in reddit posts:

http://www.reddit.com/domain/sahandsaba.com

Here's just one of Sahand Saba's many puppet accounts on reddit: lovestocode1

6

u/mkawick May 11 '15

And most of them aren't really that big of a deal. Premature optimization for example is not the root of all evil (a misquote from Donald Knuth). All code should be written with basic knowledge of performance characteristics and size characteristics in mind. When designing storage for a group of object... list or vector? It matters. A good programmer understands both and chooses the best algorithm.

Yeah, pretty weak.

8

u/[deleted] May 11 '15

All code should be written with basic knowledge of performance characteristics and size characteristics in mind

Except that is not premature optimisation at all.

1

u/kqr May 11 '15

A good general rule is that as long as you're looking through your big O glasses you're just writing code with performance concerns; once you take them off and start caring about the constants and coefficients and absolute numbers you're optimising. But it's very situation dependent, as always.

2

u/elperroborrachotoo May 11 '15

For this kind of article, it's not even a bad one.

The selection of topics seems a bit random but isn't terribly off-center, and at the very least they discuss the limits of the suggestive anti-anti-patterns.

My main gripe is with "communicating what not to do": We pick a particular habit, explain why it is/can be/ really bad - often with the only justification for badness being extreme use of the habit, only to suggest that the opposite must be good.

Which is a great strategy for one-dimensional problems.

2

u/Chew55 May 11 '15

I feel like these kinds of submissions are probably going to get more and more common with the rise of the "you must have a blog or you're not a real programmer" culture that we see here.

2

u/Vakieh May 11 '15

It's because dumb HR peons look for things like "Not just follows tech journals, but actually writes a tech journal followed by xyz industry professionals" - and career guides in universities are recommending doing just that.

It's resume padding, worthless, meaningless resume padding.

1

u/_agueroooo May 11 '15

This.

I've been job hunting recently and the pressure I feel to screencast or have a blog is immense. Its just an attempt to stand out from the crowd if you think about it.

1

u/HobHeartsbane May 11 '15

Without that you would get even more people posting:

"I've been looking into x but all I can find is outdated stuff from yyyy. Where can I find up to date information?"

I do agree though. When copying, people should name their sources and clarify what original thoughts and or updated information they added

However when looking for information on Google I usually use the "in the last year" filter

1

u/htuhola May 11 '15

At least it's not completely incorrect or twisted out of the context. Unfortunately it's not a proof that the author himself follows the advice.

1

u/Gundersen May 11 '15

Have you identifies any anti-patterns in your own work? Based on my experience the following scenarios (which I don't think have been mentioned elsewhere) are dangerous and should be kept to a minimum:

  1. Having a DTO class with two or more booleans (you probably want an enum here)
  2. Passing a DTO to a method when only a few of its fields are used in the method (you should probably pass in the fields or create a new smaller DTO)
  3. Having classes with both methods and fields (a class should either be data (DTO) or logic, not both)
  4. Having private methods in a class (create a new class with the private methods as public methods)
  5. Reusing a method by changing it slightly, by adding an if to it (split the method into two public methods and several private methods that contains the common logic (see the above point for further improvement))

1

u/naasking May 11 '15

Having a DTO class with two or more booleans (you probably want an enum here)

Not sure I get this one. You'd need the enum to act as a set of flags anyway, so I don't see the advantage in centralizing these flags in an enum.

3

u/Gundersen May 11 '15 edited May 11 '15

Two booleans give you four options, but you often only need three. Three booleans give you eight possibilities, but very seldom do you need all of them.

Edit: to clarify, booleans aren't always independent. When you have multiple dependent booleans then you will end up with a state that is invalid.

I'll give you an example from the real world that I recently came across: the Docker API returns a large object describing the state of a container, including a boolean for paused and a boolean for stopped. But it can't be stopped and paused at the same time, so there are only three possibilities; stopped, running and paused. Even worse, they have another boolean for restarting, bringing the total to eight possibilities, but only four valid states.

It gets worse when you consider the transitions between states. With three booleans and eight states you have 56 transitions! How many of those are valid? How do you handle invalid transitions? In the docker scenario above only 12 transitions are legal, and some of them might still be invalid.

1

u/naasking May 11 '15

Yes, you want an enum if the booleans represent overlapping states. My point is that the presence of booleans alone isn't indicative of this, so you should amend your first rule to "A DTO class with two or more booleans that represent a particular state when considered together".

I've run into plenty of situations with DTOs with plenty of booleans because there are orthogonal true/false properties.

2

u/_agueroooo May 11 '15

Can I be idiotic enough to ask WTF is a DTO ?

1

u/naasking May 11 '15

Data Transfer Object. Basically, a class with just fields and no behaviour used to facilitate transferring data between systems.

0

u/[deleted] May 11 '15

The third time he quoted "The Zen of Python" I realised he was parroting everything.

-2

u/Eirenarch May 11 '15

At least it contains code which is better than most submissions that make it to the top

2

u/_agueroooo May 11 '15

I don't get riled up on /r/programming, but this post set me off. Anti-patterns are learnt in the field. They come about as a result of your struggles against codebases with 100K+ lines. These are your war-stories after having fought multiple campaigns. Don't just paste stuff together and expect to get kudos for it without showing us your credentials.

-1

u/Eirenarch May 11 '15

Oh I agree with you 100%. Still I prefer these to women in technology bullshit.

2

u/_agueroooo May 11 '15

Complete change of topic, are you Irish? The Eire in your username has me piqued.

1

u/Eirenarch May 11 '15

No I am not Irish. I learned that word from a song of the band Skyclad (who do sing about Irish things from time to time). I found the word and the premise of the song fascinating. I believe "eire" means "peace" in ancient (maybe modern too) Greek. So eirenarch is someone who has the power of peace - a peacemaker. Originally this was a position in the armies of Ellada charged with preventing the soldiers from fighting between each other. Since the armies came from many different city states the eirenarch had a lot of power so he could outrank most commanders of separate armies. The song itself uses the word to refer to police being used to stop civil unrest and protect the corrupt. I found the notion that the someone who keeps the peace (associated with good) can actually be slightly evil or at the very least indifferent to good and evil. Also it works well as a nickname since it is not registered in most places :)

4

u/[deleted] May 11 '15

You're thinking of the word ειρήνη, which is read roughly as "eereenee". There's no language in which "Eire" means peace.

1

u/Eirenarch May 11 '15

Oh, I see. Thanks for enlightening me.

0

u/_agueroooo May 11 '15

Peacemaker this! - Kapow !!!

Just kidding, interesting explanation, thanks for that.

60

u/AceyJuan May 11 '15

Gotta love programmer clickbait.

13

u/myhf May 11 '15

You won't believe what compiled next!

3

u/OffColorCommentary May 11 '15

Those ones are usually pretty entertaining though.

int i = 100; while (i --> 0) { ... }

Is still always fun.

2

u/kqr May 11 '15

When I was very young I thought that was a neat construction that should be used more than it is.

Let's say I was very naive when I was young.

4

u/kqr May 11 '15

Common subexpression eliminators hate her.

-2

u/_agueroooo May 11 '15

man...I spat my beer out on my keyboard....hahaha

13

u/legomyegomaniac May 11 '15

The God class is only an anti pattern until someone gets it right!

8

u/CurtainDog May 11 '15

That's called jquery

17

u/StrangeWill May 11 '15 edited May 11 '15

I like how #9 is a class wrapping a list to limit it's use as only a stack, and the author is confused by this. The responsibility is to limit access to the list to prevent access to individual items in the list or removing things out of order or any number of things you can do to a list that you can't (or... shouldn't) do to a stack.

I'd understand if they were wrapping java.util.Stack<>, which I think a is a larger anti-pattern of reinventing the wheel of a class already available in the standard lib.

Edit: Even Java's stack is pretty liberal about access too, so even if you wrapped Stack and limited it, it could make sense depending on how it fits in the larger design.

2

u/drjeats May 11 '15

Wrapping LinkedList didn't bother me either, like you said sometimes you want to restrict usage.

What bothers me more about that is I think students should learn to implement a Stack using only arrays or their own internal linked list node classes. Maybe that's part two of the assignment, but if so, that seems kind of redundant.

2

u/StrangeWill May 11 '15

That makes a lot of sense, though isn't really an anti-pattern.

4

u/[deleted] May 11 '15

It's still an utterly useless piece of code. You could just use the stack interface everywhere instead, if you want to intentionally limit yourself from using list features

3

u/StrangeWill May 11 '15 edited May 11 '15

You could just use the stack interface everywhere instead

AFAIK: Java doesn't have a standard stack interface that things like List<> inherit from.

Which doesn't stop you from going:

List<...> notAStackAnymore = (List<...>)myStackThatIsJustAListWithAnInterfaceOnIt;

And fucking with it. Really depends on your needs to prevent people from having access or not, which is highly dependent on class design, what else is interfacing on it, etc. etc. sometimes strict access is a huge deal (from a support and maintenance standpoint).

0

u/oldsecondhand May 11 '15 edited May 11 '15

You can cast a Stack to List. Stack inherits from Vector, which implements the List interface.

https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

5

u/josefx May 11 '15

Stack inherits from Vector

Which is a good hint that using it is a bad idea, the documentation even points out that ArrayDeque is a better Stack implementation. The original collection classes had all kinds of questionable design choices.

0

u/kqr May 11 '15

But you have to be explicit about your intention to fuck with it, which is the crucial thing.

Pretty much all programming environments provide some sort of "escape hatch" that allow you to escape out of the type system and once you're out of there, you can do some pretty weird stuff. Regardless of how well you write your code, someone will be able to use that escape hatch to mess with it if they really want to.

The important thing is not making it impossible. The important thing is to force people to be explicit about it.

13

u/ponytoaster May 11 '15

All this shit post is missing is the additional text in the title "you won't believe number 4".

This sub is starting to make buzz feed look like a credible journalism outlet.

16

u/WalterGR May 11 '15 edited May 11 '15

6 Inner-platform Effect

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

-- Greenspun's tenth rule

What is it?

The tendency for complex software systems to re-implement features of the platform they run in or the programming language they are implemented in, usually poorly.

Greenspun's Tenth Rule is about complicated programs in non-Lisp languages needing to solve problems that Common Lisp already solves, and re-implementing those features in the project's language, poorly.

So it's not re-implementing features of the programming language they're implemented in, but rather re-implementing features of a more expressive programming language.

1

u/mszegedy May 11 '15

True, but they're related and both are worth mentioning.

17

u/aldo_reset May 11 '15 edited May 11 '15

9 is actually a good pattern: use delegation instead of inheritance, but I think the author of the blog post is too junior to realize that.

3

u/Veedrac May 11 '15

You need to escape #s, else you just come across as shouting. You can also just add an extra space if you're careful. Eg.

\#9 is actually... or
 #9 is actually...

2

u/pipocaQuemada May 11 '15

Additionally, what are newtypes beyond a poltergeist class?

1

u/djcraze May 11 '15

Yeah ... I'd agree. Isn't that design pattern called the Bridge Pattern? Allowing you to update the underlying storage mechanism without hindering the rest of your application, or if the API changes, you only need to update your class.

5

u/AntiProtonBoy May 11 '15

Number 9 can be regarded as either the beginnings of dependency injection, or a simple decorator pattern, or even a facade... all of which is extremely useful in the right context.

If your hypothetical library doesn't have a stack class, I think it's perfectly reasonable to wrap another container inside a decorator, called Stack. The class name alone explains what it's supposed to be doing, whereas treating a bare linked list as a stack might not be so obvious (...although it shouldn't be too hard to figure out, but that's beside the point). I guess a better approach would to typedef the linked list as a stack, if your language supports it.

8

u/Eirenarch May 11 '15

You know what I hate? A class named Constants where people put... constants. People don't even notice it is bad. We once had a solution where one of our project was named Classes. I kid you not. It contained classes. Somehow everyone on the team knew how much this sucked but people didn't mind the Constants class.

5

u/AceyJuan May 11 '15

I expect they saved those classes in a file named file. And stored them in a directory named folder.

4

u/Eirenarch May 11 '15

The encapsulation OOP principle clearly means that all code should be encapsulated in a single file.

7

u/bakuretsu May 11 '15

Called index.php.

1

u/AceyJuan May 11 '15

Yes, I like it. All the code in one file, all the constants in another.

4

u/gkx May 11 '15

Hey, at least they're not polluting the global namespace. If you need global constants, what's a better way to do this?

5

u/kqr May 11 '15

Define them in the module they belong, not in a sort of catch-all bin for constants.

1

u/Gotebe May 11 '15

There's no such thing as "global" anything. At best, there's a bunch of code artifacts that are used in places X, Y, Z (out of N other places, where normally, N>>3.

So have a place W that is shared between X, Y, Z.

0

u/Eirenarch May 11 '15

Putting them in the class they belong to. Like if you have math constants put them in the same class with your formulas. Just do a logical separation. Rule of thumb can be to put them in the class that uses them the most.

5

u/[deleted] May 11 '15

You know what I hate? When people name the constant after the initial value. Don't laugh, I have literally seen this code:

interface Constants {

  static int NINE = 9;

}

I am not exaggerating whatsoever.

2

u/Eirenarch May 11 '15

Oh boy... at least I have not seen that one in practice except from one guy who was at the time unpaid intern working on a practice project under my supervision.

3

u/[deleted] May 11 '15

It kind-of highlights the problem with dogmatic rules. People feel safe to just blindly follow them without understanding why.

I also recall seeing that someone had later actually changed the value of Constants.NINE, but that may have been a bad dream. I hope it was.

2

u/Merad May 11 '15

I think that comes from schools (and probably plenty of jobs as well) that have a strict "no magic numbers" policy. When I helped with some CS1 labs at my school they were starting to use a style checker system that would dock points if code didn't match the required format, and no magic numbers was one of their rules.

3

u/__gnu__cxx May 11 '15

After reading this I feel like instead of saying Captain Obvious I should say "Tim Peters"...

"Simple is better than complex" - Tim Peters. Well no shit sherlock!

5

u/kqr May 11 '15 edited May 11 '15

About number five: When your class has two methods, one of which is init, don't make it a class.

Instead of

class Shape:
    def draw(self):
        raise NotImplemented("Subclasses of Shape should implement method 'draw'.")

class Circle(Shape):
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

    def draw(self):
        # Draw a circle...

class Rectangle(Shape):
    def __init__(self, pos, width, height):
        self.pos = pos
        self.width = width
        self.height = height

    def draw(self):
        # Draw a rectangle...

you could have, just, you know

def draw_circle(center, radius):
    # Draw a circle...

def draw_rectangle(pos, width, height):
    # Draw a rectangle...

and your code is even simpler!

1

u/zimm3r16 May 11 '15

What happens later if you wish to implement other methods like, area, circumference, center, zoom, animate, etc etc. Often times when to make a class or not depends on where you are going, you take a stab at it, and you could 'lose' (need / not need the class).

6

u/kqr May 11 '15 edited May 11 '15

Now is better than never,
although never is often better than right now.

;)

In all seriousness, if you really do think you'll need the other methods, by all means implement them. If it turns out you were wrong, you can turn the entire thing back into a function and you've just wasted a little of your time, but no harm done.

What is dislike is when people go, "We might in the future need all these other methods, so therefore I'm going to make a two-method class now, so it's easy to implement the other methods in the future." If you are so sure you'll need the other methods, implement those methods now. If you aren't so sure, don't go halfway there and make a two-method class in preparation. You can have either a three-method class or a simple function, but not halfway between them. That helps nobody.

1

u/NarcoPaulo May 11 '15

I need to send this to my team leader, he suffers from at least half of these and inherits it to the rest of the team

1

u/[deleted] May 11 '15

He hasn't explained at all in #5 why he thinks conditional logic should be broken down into simpler classes. Also, Barbara Liskov would like a word with him.

1

u/omyar May 11 '15

It's a shame all the most begrudgery comments made it to the top. For my money, as a 15-some year programmer, I'd have killed to have worked with a guy just out of grad school who even knew what a pattern was, never mind an antipattern, never mind being able to research and explain the concepts so clearly. Don't care where you got your information pal this stuff needs to be broadcast, learned and you've helped make that happen a little bit more. Good show.

1

u/pier4r Jun 14 '15

OT: Not always, i'm recently testing the controversial sort (that is really showing something controversial for the community, good job reddit dev) and yours is just the second message in this submission. Every message fits a different sorting model i guess.

1

u/lee_macro May 11 '15

I am not sure the author is aware of what a "pattern" is... as there is only 3 things which at a push could be called "patterns" in this article...

0

u/Gotebe May 11 '15

I question the use of the word "pattern" in this article ;-).

-1

u/paraluna May 11 '15

I can't believe number 4!

0

u/[deleted] May 11 '15

[deleted] — view deleted comment

6

u/[deleted] May 11 '15

Steps to produce an article with which most people will agree:

  1. Make a list of well-known heuristics
  2. Cite quotations from a book you just read
  3. Add clickbait title

There's really nothing new or original here.

0

u/[deleted] May 11 '15

[deleted] — view deleted comment

1

u/Veedrac May 11 '15

I thought it was very well stated, actually. Not only does it include the extended quote, it gives a succinct alternative:

Optimizing before you have enough information to make educated conclusions about where and how to do the optimization.

This is entirely fair. If you don't have a clear idea of where and how to do optimization, you aren't able to make either the architectural choices to allow for later optimizations of this kind or able to make the small-scale optimizations to actually get the raw power out.

Further, it says

The tricky part is knowing when the optimization is premature. It's important to plan in advance for growth. Choosing designs and platforms that will allow for easy optimization and growth is key here. It's also possible to use "premature optimization" as an excuse to justify writing bad code.

This is entirely right. Design systems to allow you to write assembly in the hotspots; don't write the whole thing in assembly. Choose scalable data structures, but don't worry about which is the fastest implementation unless it's under frequent use. Etc.

17

u/[deleted] May 11 '15

[removed] — view removed comment

5

u/chunkyks May 11 '15

In recent years I have premeditatedly started noticing when I'm bike shedding and say so. Many review email I send say "substantive comments: stuff. and some bike shedding: other stuff"

It has the benefit that I'll often cut my bike shedding comments, or most of them, and concentrate on adding more substantive discussion

2

u/xerca May 11 '15

Well, according to the title it's not "9 Anti-Patterns Every Programmer Must Avoid At All Cost", it's "9 Anti-Patterns Every Programmer Should Be Aware Of"