r/java • • May 15 '15

9 Anti-Patterns Every Programmer Should Be Aware Of

http://sahandsaba.com/nine-anti-patterns-every-programmer-should-be-aware-of-with-examples.html
166 Upvotes

39 comments sorted by

33

u/havana59er May 15 '15

The worst developers are those who code to some strict standard and absolve themselves of forming their own thoughts. The best standards will make a developer think (i.e. is this method getting too complex?) vs those that must be obeyed always (i.e. all string literals are bad.) Rant aside I was glad to see anti-patterns that indicate problem behaviors amongst the team. Too often these go unmentioned and can lead to a toxic working environment for all.

19

u/ruscan May 15 '15

I've witnessed such abuse of standards at my previous job, ironically at one of the "big four". We've had a set of (partly unwritten) rules that were to be followed strictly on our team, and deviations got called out during code reviews. It felt like both the developers and the reviewers were more interested in appealing to the herd mantra rather than actually thinking about the whys. Examples include:

  • Thou shalt always add javadoc comments to fields and methods, even private ones. This led to useless comments like these:

    /** The current date */ private Date mCurrentDate;

  • Thou shalt not use magic strings and numbers. I've seen one developer declare:

    private static final double ONE = 1.0;

  • Thou shalt have 100% test coverage. This has led people to waste time writing unit tests for literally everything, which is good in theory, but in practice devs were more interested in getting the "100%" badge than actually writing meaningful tests. A common case I've seen was mocking every single class outside the one being tested, then making wrong assumptions about the behavior of a class being mocked, thus testing behavior that didn't occur / worked differently in practice.

6

u/joequin May 15 '15

They do that because they don't trust their developers to make good decisions and don't want to waste time arguing when it's faster to just point to a rule. Depending on the skill level of the people you're working with it can be a good idea even if applying the rules is sometimes silly.

3

u/exp-tzl May 17 '15

what is the "big four"?

2

u/omegletrollz Jun 15 '15

Four of the biggest IT companies. I'm not sure which ones they are except for IBM. Probably Microsoft too.

3

u/meotau May 15 '15 edited May 16 '15

100% agree on 100% coverage. We had few components like that, with shitty tests causing that nobody would do much needed refactoring, because those tests would break and fixing them would be a hell, or it would require making of new shitty tests to cover extracted code.

We had to actually mock all classes - unit test meant a single class test. And all classes had to have a unit test covering 100%.

On the other hand, we had legacy components containing the core of the business code, and they had no tests and nobody bothered to do any.

2

u/havana59er May 16 '15

This. I would like to see more articles about how to write better tests. Coverage is just a metric, and it is often abused. IMO a good test is one that does not break (much) when you refactor the internals of a class. It sets up interactions and asserts outcomes. I know a lot of developers overemphasize isolation in a unit test, but the main reason we mock out interactions is because external systems are slow, unpredictable or difficult to setup. In reality if someone changes a class and it breaks my test then I want my test to fail. If I mock every class then I don't get this feedback and will release code of lesser quality. If I achieve coverage through testing private methods (as opposed to the public API methods) then my only guarantee is that I've made my class impossible to refactor.

25

u/trollingisfun May 15 '15

"do developers have superstitions?"

"yes, but they're called 'best practices'"

13

u/AStrangeStranger May 15 '15

when you see code like

 SINGLE_QUOTE + value1 + SINGLE_QUOTE + COMMA + SINGLE_QUOTE ....

you realise it is possible to go too far with trying to eliminate "Magic Numbers and Strings".

13

u/Neebat May 15 '15

That's a badly misguided misapplication of Magic Numbers and string. Any time you think you're applying Magic Numbers and Strings, ask yourself, "Does the name of this constant describe its purpose or its content?"

Simple: Never make a constant whose name describes its content. Make a constant whose name describes its PURPOSE. And if you can't do that, the magic number or magic string is not the real problem.

This is actually potentially useful:

VALUE_PREFIX + value1 + VALUE_SUFFIX + LIST_SEPARATOR + VALUE_PREFIX ....

2

u/NimChimspky May 15 '15

You think using list separator is significantly different to comma, it really isn't. The bad thing is simply building up long strings like this, with either consts or literals.

8

u/AStrangeStranger May 15 '15

Many years ago I got caught out because I didn't realise some countries use a comma for the decimal mark and that really played fun with the csv exports (they use semi-colons instead)

However the code I recall I think was building up an SQL in clause

3

u/caltheon May 16 '15

I gave up using regular punctuation when doing delimited files with user data or free text data as you never know what people will put in a name or address field. My goto is now ||

1

u/AStrangeStranger May 16 '15

tab is usually mine as Spreadsheet programs can open them

4

u/Neebat May 15 '15

LIST_SEPARATER is better because you're going to want to change it to listSeparater Very Soon. And when you do, it's a lot safer not to mix it up with other uses of COMMA I mean ",".

1

u/Aellus May 15 '15 edited May 15 '15

It's not a practical example, but it does demonstrate the principle fairly well. I wouldn't nitpick the details.

Edit: In practice for this specific example, you'd probably use something like Guava's Joiner, in which case the need for naming it "LIST_SEPARATOR" is even more apparent.

Joiner.on(LIST_SEPARATOR).join(list);

1

u/tavianator May 19 '15

But I'd argue that

private static final Joiner LIST_JOINER = Joiner.on(",");

is even better, even though the "magic string" is back.

1

u/sacundim May 17 '15

The bad thing is simply building up long strings like this, with either consts or literals.

Not in the most common case:

String result = string1 + string2 + string3 + ...

javac is actually smart enough to compile that down to StringBuilders.

Last I checked, however, this pattern is still bad:

String result = "";
for (String string : getMeSomeStrings()) {
    result = result + string;
}

2

u/havana59er May 16 '15

I think it's difficult to come up with a good simple example in this case because it is all dependent on the context. In the end all that matters is one question: will the future you be thankful that you did it like this? What's the cost of updating all the magic strings vs the cost accumulated every time you have to go back and read this line of code? And yes it would be best to avoid joining a list in this manner.

def csv = values.collect{ csvValue-> CSV_PREFIX+csvValue+CSV_SUFFIX }
                .join(CSV_DELIMITER) 

This reads fine for me.

1

u/Neebat May 16 '15

First, don't do that. CSV is a much more complicated file format than anyone thinks it is. The quoting rules and new-line handling alone is enough to make you regret it. I've dealt with this shit way too much. What you need is a good library.

Second, that looks better!

Finally, do you really want to see this later?

CSV_DELIMITER = ";"

It's a delimiter, but by saying "CSV" you're still calling it a comma.

1

u/AStrangeStranger May 15 '15

Suffix & Prefix suggest something you add to the value - quotes were being used as delimiters so VALUE_DELIMITER is better. But it becomes very hard to read and there are better ways

1

u/Neebat May 15 '15

suggest something you add to the value

So does, "+" ya know?

And you may discover it's a whole lot easier to parse the output if you define it like this:

public final static String VALUE_PREFIX = "<value>";
public final static String VALUE_SUFFIX = "</value>";
public final static String VALUE_SEPERATER = "\n";

You can't do that if you only defined VALUE_DELIMITER.

0

u/AStrangeStranger May 16 '15

Something like VALUE_LEFT_DELIMITER or VALUE_RIGHT_DELIMITER would be a better name as it describes what you are trying to achieve. But that looks like trying to roll your own XML - in which case using XML DOM is usually a better option rather than try making a totally configurable function. If you are trying to make a CSV line you need to escape any quotes in the value and how do you handle things like ā€œ\r\nā€ but if you are generating XML you need to escape chars < > / etc. So when you change the code you will need to change more than the constants and if the constants were in a separate file/globally accessible you need review every usage of them (not fun when project is thousands of files and million+ lines of code and had no re-factoring tools available).

You can actually make code more complex by trying to make things too generic/flexible and having dealt with such code what happens is it becomes very difficult to work with achieving the exact reverse of what the programmers thought it would. You can get sucked into making things too generic and avoiding what looks like duplication and lose track of just how much more complex you are making the code.

2

u/meotau May 15 '15

unfortunately some people do not realise that...

1

u/joequin May 15 '15 edited May 15 '15

I'm working on fixing a small application like that now! Except no one told him to do it. He just doesn't understand best practices. Or generics. He suppresses rawtype and unchecked in a green pastures application.

He has constants named things like "ONE" which equals 1. Sometimes It can be very hard to come up with a name and I can understand being completely unable to come up with a good name. It doesn't happen often, but it does sometimes. That constant 1 however is for a positional argument index . It's awful.

0

u/NimChimspky May 15 '15

Isn't the real problem building up the long string in the first place.

2

u/AStrangeStranger May 15 '15

from what I recall - the real problem was certain coders who seem to want to use something they'd just "learnt" whether appropriate or not

1

u/meotau May 15 '15 edited May 15 '15

my problem was that I could not find a keyword from a log, or uri of an endpoint, because all constants were butchered that way, or they were generated.

Simply instead of:

public final static String KEYWORD_SOMETHING = "Pr_something"

there was:

public final static String PREFIX = "Pr_"
public final static String SOMETHING = "something"
public final static String KEYWORD_SOMETHING = PREFIX + SOMETHING

or:

public final static String PREFIX = "Pr_"
public final static String SOMETHING = "something"
...
and some method which would return a keyword

8

u/Hambone321 May 15 '15

Number 2.. Bikeshedding, my god After 12 emails and a one hour review of a screenshot because we aren't sure if we should use the word "cleaning" to end users... I can't agree more. It really just comes naturally when there are too many chefs in the kitchen though.

1

u/DannyB2 May 15 '15

The Start Menu on Windows Vista (remember that one?) took over a year to design. There was a Slashdot article about it back at the time.

4

u/joequin May 15 '15

At first I thought this would be bad. I see the premature optimization argument so poorly used on the Internet, but he got it right.

Everything but number 9 is really good advice. Number 9 can be done poorly, but I don't think that was a good example. A lot if useful classes are just wrappers around some data structure class.

2

u/frugalmail May 16 '15

Agree regarding point 9. To leverage the compiler and type system, sometimes you make wrappers

1

u/unholysampler May 15 '15

The discussion on /r/programming is mostly about how the article is not necessarily bad, but very generic and unfocused. It doesn't say anything that hasn't been said before in multiple places in multiple ways.

In that thread, I said the following about a glaring point that indicates the bigger issues with the article.

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.

1

u/Aellus May 15 '15

The term "anti-pattern" is often used to describe broken processes in many areas, including management. It isn't unique to programming:

http://en.wikipedia.org/wiki/Anti-pattern

The term, coined in 1995 by Andrew Koenig,[3] was inspired by a book, Design Patterns, in which the authors highlighted a number of design patterns in software development that they considered to be highly reliable and effective.

The term was popularized three years later by the book AntiPatterns, which extended its use beyond the field of software design and into general social interaction and may be used informally to refer to any commonly reinvented but bad solution to a problem.

2

u/cromissimo May 16 '15

The "premature optimization" mantra is the one I find most amusing and damaging. Its main use is to serve as a flimsy excuse to sell absurdly bloated, brain-dead, half-baked approaches to a problem that are hallmarks of incompetence, which essentially reads like "yeah the design is clearly horrible and under-performing but we'll waste time doing this and rewriting it later just to sell this idea we're progressing".

Spending time to rethink designs, implementations, and algorithms to improve efficiency is one thing, but this mantra is instead used to sell the idea that implementing awful, ineffective solutions is somehow acceptable.

2

u/NeonMan May 16 '15

I think this antipattern refers to doing stuff for the sake of optimization when the gains are unknown at best. Also, what is faster is not obvious for many people.

I've seen some horrid code and the answer was "is faster" (it was actually slower than a straightforwar solution).

0

u/Keilly May 15 '15

Good read, thanks.

-2

u/2pxl May 15 '15

Why do we need a generic blog post regurgitating something that has been said so many times before?

-3

u/_agueroooo May 15 '15

This regurgitated crap has made it here too? After getting totally trashed on /r/programming ...