r/badcode • • Aug 17 '20

java Todo: less dirty.

Post image
788 Upvotes

53 comments sorted by

132

u/[deleted] Aug 17 '20

I don't think this is bad code. It's very clear what's happening. You could do a bunch of checks, but possibly if the values are within just this range, then I think this is fine.

104

u/mind_overflow Aug 17 '20 edited Mar 01 '22

I don't know if you actually read all numbers, but what I noticed is that they are all multiples of 9, plus 3, 4, 5, 6, 7 and 8 every time.

I haven't invested much time in this since it's a very old project I made and at that moment I just needed a quick way of testing if everything worked, however something I'd use today is probably

public static int incrementHelPos(int currentPos)
{

    int remainder = currentPos % 9;
    if(3 <= remainder && remainder <= 7)
        return currentPos + 1;
    
    return currentPos + 4;
}

11

u/[deleted] Aug 17 '20

Good point. Looking over this, the case for returning 3 isn't covered in your snippet

13

u/mind_overflow Aug 17 '20

"return 3" was used as a fallback to start the loop again in case the calling method was giving a currentPos higher than the handled ones. this caused the loop to start again from pos 3, overwriting the previously written data. the method is "increment pos", so it shouldn't start back from 3. it should just continue and eventually overflow, letting the dev know something bad happened. however, this was not possible before, since the numbers were hardcoded in the function :P

54

u/jonathanhiggs Aug 17 '20

It is one of those examples that looks a little verbose and not quite a smell when it is devoid of context, but when you have the context the 3 <= (pos % 9) <= 7 would have some meaning and be more obvious

24

u/carfniex Aug 17 '20
1 test(s) failed:
assertEquals(3, incrementHelPos(37));

16

u/cadatoiva Aug 17 '20 edited Aug 17 '20

He's not off base with the pattern, but he is off base with the implementation. This would ensure everything works correctly.

public static int incrementHelPos(int currentPos)
{
    int rest = currentPos % 9;
    if(rest < 3 || currentPos >= 44)
        return 3;
    if(rest < 8)
        return currentPos + 1;
    return currentPos + 4;
}

(Edit) He does say in another post that the default case is there to manually overflow the variable because of the hardcoded switch conditions though, so his implementation is within the true intended spec.

4

u/crowbahr Aug 17 '20

Your assumption is that the function returning 3 is spec rather than an error :)

28

u/carfniex Aug 17 '20

when working with legacy code, the spec is how it currently works

3

u/the_d3f4ult Aug 17 '20
if (++x % 9 > 4) x += 3;

or

return (++x % 9 > 4) x + 3 : x

idk but I haven't tested it...

2

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/mind_overflow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

17

u/weeknie Aug 17 '20

If there was absolutely no pattern to this list, then maybe this would be okay. But you should look for a way to solve this mathematically first, and as OP pointed out, you can find one with 10 seconds of thinking.

8

u/BOSS_OF_THE_INTERNET Aug 17 '20

Never conflate verbosity with bad code. I would argue that this bad code is the unfortunate downstream result of bad design.

11

u/OscariusGaming Aug 17 '20

This is absolutely bad code. People often use switch statements when they really should be using arrays instead, and this is not an exception.

let firstArray = [3, 4, ... 42, 43]

let secondArray = [8, 17, 26, 35]

if (firstArray.contains(currentPos)) {
    return currentPos + 1
} else if (secondArray.contains(currentPos)) {
    return currentPos + 4
} else {
    return 3
}

Of course, if you can check which group the number belongs to mathematically, that's even better since it condenses the code even more, and more importantly gives an insight as to why it belongs in that group.

14

u/OmnipotentEntity Aug 17 '20

A switch statement is an O(1) array lookup in a jump table. An array.contains check is O(n), and contains one extra unpredictable branch in a loop, almost requiring a branch prediction failure.

As others have pointed out, there is a math based O(1) formulation, and that's better than the switch statement. But array.contains is, imo, strictly worse than the switch statement if this code is hot.

If it's not hot then it's much more readable, but still not as good as the math.

3

u/OscariusGaming Aug 17 '20 edited Aug 17 '20

From Wikipedia - Branch Table:

It relies on the fact that machine code instructions for branching have a fixed length and can be executed extremely efficiently by most hardware, and is most useful when dealing with raw data values that may be easily converted to sequential index values. Given such data, a branch table can be extremely efficient.

This means that it's only O(1) if your cases can be easily converted to sequential index values, with the keyword being easily. Now, I don't know how all compilers do this but I would guess they're not going to try anything more advanced than a linear map (this also brings us back to the original problem of the math based formulation). But that is besides the point. Unless it is going to run on an embedded system where performance is super critical, it isn't going to make a big difference. To quote Don Knuth: The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.

Edit: As /u/OmnipotentEntity correctly pointed out below, some compilers do indeed find ways to express a mathematical formulation for this problem, and I stand corrected.

5

u/OmnipotentEntity Aug 17 '20 edited Aug 17 '20

This means that it's only O(1) if your cases can be easily converted to sequential index values, with the keyword being easily. Now, I don't know how all compilers do this but I would guess they're not going to try anything more advanced than a linear map (this also brings us back to the original problem of the math based formulation).

https://godbolt.org/z/KKPhTG

MSVC create a jump table out of the switch code. GCC optimizes it into math. Clang optimizes it to a simple array lookup.

Clang and GCC unrolls the loops in the array check version and you just have a huge if-else block. MSVC on the other hand just walks the loop without even unrolling.

Finally, the math block compiles into math on all three compilers, because it already is, but if you look at the math between the GCC switch version and the GCC math version, the switch version actually results in cleaner assembly code. (Which surprised me, but it makes sense. The math version posted up thread does force the compiler to obey certain restrictions, such as short circuiting the or statement and so on. But the difference is probably not enough to show any real performance test unless this is in a tight inner loop.)

But that is besides the point. Unless it is going to run on an embedded system where performance is super critical, it isn't going to make a big difference.

I literally said "if this code is hot." You're not finding a point of disagreement, you're finding a point of differing emphasis. My central point isn't "huge switch statements are awesome." My central point is "be mindful of hiding (algorithmic) complexity in small functions where it is not necessary."

Premature optimization may be the root of all evil. But writing code that is slow when writing better code is literally easier is also unacceptable.

(EDIT Final: After several edits to this post, I'm done fucking with it.)

(EDIT Again: I lied, corrected some interpretations of the assembly that I had mistaken because I was reading it too fast.)

3

u/OscariusGaming Aug 17 '20

I didn't know that, thanks for the insight!

3

u/m_domino Aug 17 '20

I will never not upvote people stating "I stand corrected".

0

u/[deleted] Aug 17 '20

[deleted]

1

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/OscariusGaming, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

15

u/W2Wizard Aug 17 '20

What's the thing you guys use for these snippets?

28

u/mind_overflow Aug 17 '20

3

u/[deleted] Aug 17 '20

Carbon | Create and share beautiful images of your source code

That just looks like a iTerm2 screenshot on macOS like here

1

u/mind_overflow Aug 18 '20

oh well. I'm pretty sure that's where the idea came from 😂

48

u/thisonehereone Aug 17 '20

You can add ranges to case statements in more modern versions of c#. So you could knock this down to 5 cases in the top section.

case int n when (n < 8 && n >= 3 ):
case int n when (n < 17 && n >= 12 ):
case int n when (n < 26 && n >= 21 ):
case int n when (n < 35 && n >= 30 ):
case int n when (n < 44 && n >= 40 ):

I would prefer to know what the ranges mean though. Why are some +1 and others +4? That's what helps it make sense.

15

u/cadatoiva Aug 17 '20

Language is Java, not C#

His other comments show that it's mod 9 and it increments from 3-8 and then the +4 skips 0-2 of the series.

4

u/thisonehereone Aug 17 '20

I see. But still I want a why in my code.

10

u/mind_overflow Aug 17 '20 edited Nov 24 '21

Ok, here goes the explanation.

The software I was working with had a table, however the only way to access data in that table was by the data's index in the table, starting from 0 (much like an Array, visually represented as a Table however). The table had 9 columns, and I had to leave the first 3 empty. example:

| 0  | 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  |
| 9  | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |

etc. so the only indexes I needed were (3, 4, 5, 6, 7, 8) and a sum of 9 (repeated an increasing number of times) plus the base index number. So the formula is: [9x + index], where 3 <= index <= 8.

I had to leave columns (0, 1, 2) empty because they already had important data.

There you go!

10

u/FrostBite_97 Aug 17 '20 edited Aug 18 '20

Do this

If v%9>=0&&v%9<3
    Return 3;
Else if v%9 3-7
    Return cnt+1
Else return cnt+4

I wrote on mobile the formatting sucks I know.

1

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/FrostBite_97, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/[deleted] Aug 18 '20

[deleted]

2

u/FrostBite_97 Aug 18 '20

Oh wait yeah. Contributing to the sub in my own way i guess!

0

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/mind_overflow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/Mexenstein Aug 17 '20

Java, Microsoft Java, tomatoe, tomato.

0

u/cadatoiva Aug 17 '20

Normally, I would agree. But this feature is not present in both, only in c#.

4

u/Mexenstein Aug 17 '20

It was a joke, but I'm learning that this sub has a low tolerance for those. Every time I make one I get downvoted. Hope this time it's lesson learned.

2

u/[deleted] Aug 17 '20

I dont know to much about switches, but whats the point of having all those checks that dont do anything? Like wouldnt you only need to have cases if it does something?

4

u/mind_overflow Aug 17 '20 edited Aug 17 '20

Switches work in a weird way, very different from if statements. Switches (or actually, cases) work until they hit a break; or return; statement. What it means is that:

switch(number) {
   case 1:
   case 2:
   case 3:
      return "AAA";
   case 4:
      return "BBB";
   default:
      return "CCC";
}

if the given number is 1, 2 or 3, then the code is executed until return "AAA"; is hit. so, even if directly after case 1: I don't write some code, it still executes the first code that it finds, until a break; or return; statement is reached. If no condition is met, the default code is ran. so:

- 1 -> AAA
  • 2 -> AAA
  • 3 -> AAA
  • 4 - > BBB
  • 0, 5, 6, 7, ... -> CCC

Hope this helps!

EDIT: formatting

3

u/[deleted] Aug 17 '20

Ooooh thats helps alot actually, is there no way to do something like case: <=3 though? Anyways, thanks

2

u/[deleted] Aug 17 '20

Yes, yes there is. It's called an if statement.

0

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/mind_overflow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/-Dueck- Aug 17 '20

What exactly is a Hel position? I assume that's short for something?

2

u/mind_overflow Aug 17 '20 edited Mar 01 '22

correct, that's short for something. I don't remember very well (the code is obviously undocumented), but it was something along the lines of "horizontal elements position", which actually makes the code look even worse. because:

  1. I'm dealing with a table, not anything linear (?)

  2. If I ever had to give it that name, it'd be incrementHElPos()(with capital E), if not incrementXElPos() at best (or incrementElementPosX()).

1

u/TastyDumplingSoup Aug 17 '20

What the fuck?

3

u/mind_overflow Aug 17 '20

I mean, that's why we are all here, you shouldn't be surprised :lmao:

2

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 06 '20

Image Transcription: Code


public static int incrementHelPost(int currentPos) // todo: less dirty
{
    switch (currentPost)
    {
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
        case 21:
        case 22:
        case 23:
        case 24:
        case 25:
        case 30:
        case 31:
        case 32:
        case 33:
        case 34:
        case 39:
        case 40:
        case 41:
        case 41:
        case 43:
            return currentPos + 1;
        case 8:
        case 17:
        case 26:
        case 35:
            return currentPos + 4;
        default:
            return 3;
    }
}

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

3

u/[deleted] Aug 17 '20

I see you found more Yandre Sim code. /s

1

u/mrtailsjs OH GOD Aug 27 '20

well, yes, but no

0

u/[deleted] Aug 17 '20

[deleted]

1

u/AutoModerator Aug 17 '20

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/mind_overflow, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.