r/ProgrammerHumor • • Jan 18 '23

Meme its okay guys they fixed it!

Post image
40.2k Upvotes

1.8k comments sorted by

6

u/BearTM Jan 19 '23

Why not implement it using a single Substring?

private static string GetPercentageRounds(double percentage)
{
    return "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪".Substring(10 - (int)Math.Ceiling(percentage * 10), 10);
}

1

u/ohsangwho Jan 19 '23

thats beautifully clean, this is the cleanest I've seen in the comments I've looked at

→ More replies (1)
→ More replies (1)

3

u/LoyalSage Jan 19 '23

Here’s a different solution just for fun:

  1. Start with a string literal “🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️”.

  2. Multiply the percentage by 10 and floor (or round however you like to get the number of filled circles you want as an int). Call this number i.

  3. Return the substring from index 10 - i to 20 - i.

Or something like that.

1.3k

u/nevergrownup97 Jan 18 '23 edited Jan 20 '23

For anyone thinking “pathetic, who renders progress bars with emojis”: this might be for an NFC eID reading status on iOS. The iOS NFC handler popup view only supports text-based content, so Unicode is the only way to implement a visual reading progress indicator.

EDIT: https://is2-ssl.mzstatic.com/image/thumb/Purple122/v4/f3/be/68/f3be6868-a7b2-50d0-3a12-b989e545ffd0/19d7b166-55a7-4554-8c7d-48a973f7b379_app_images_1242x2688-04.png/300x0w.jpg

→ More replies (12)

2.5k

u/[deleted] Jan 18 '23 edited Jan 18 '23

Sees this code that displays circles:
The entire internet wants to review it and has strong opinions about it.

Sees a 500 line PR that handles money transactions:
LGTM, approved

604

u/crass-sandwich Jan 18 '23

184

u/motie Jan 19 '23

Thank you for introducing me to the law of triviality.

55

u/TheCorruptedBit Jan 19 '23

bike shedding and farding

33

u/Tjep2k Jan 19 '23

I read bike shredding and was confused for a moment.

→ More replies (2)
→ More replies (3)

61

u/darthwalsh Jan 19 '23

Today we had 3 engineers and a PM at a meeting, already 5 minutes past the scheduled end date. We're looking at a Jira issue that we've already added to the current sprint, when somebody comments we change a word in the title. This turns into a little argument, trying to decide if "in" or "for" etc is best.

I kid you not, we wasted 2 minutes deciding on which preposition would go in the title of a ticket that's never going to be seen again after this sprint.

I had already interrupted once to suggest we move this conversation to Slack. It doesn't feel like a good career move to repeatedly interrupt your boss to tell them that they're not making good use of company time.

9

u/mafilter Jan 19 '23

“Rabbit Hole” - your PM should’ve pulled up the bunny card.

→ More replies (1)
→ More replies (3)

12

u/Existing_Imagination Jan 19 '23

More like *ignores PR and waits until other people get to it instead

→ More replies (1)

0

u/[deleted] Jan 18 '23

[deleted]

48

u/Mitoni Jan 19 '23

You joke, but I've been contracted for one of the largest financial firms in the world, and they still will spend like less than a half a day regression testing a while release because they are rushing to get it into prod, and then wonder what happened when bugs are discovered after the prod release.

→ More replies (3)
→ More replies (3)

7.2k

u/TwoMilliseconds Jan 18 '23

well it's... faster

907

u/rickyman20 Jan 18 '23

Is it though? I feel like a compiler could optimize the former to an O(1) jump table, but the latter has to stay O(logn) unless your computer is a fucking god. Also fewer jumps is usually better

572

u/Noch_ein_Kamel Jan 18 '23

Can it do jump tables with floating point input?

→ More replies (81)

53

u/Disastrous_Being7746 Jan 18 '23 edited Jan 18 '23

If it's smart enough to do the math to convert the floating point percent to an integer by multiplying by 10. Otherwise, there's still comparisons going on.

Edit: I don't think it would be as easy to do this with how the conditions are.

The conditions are like percent > 0.0 && percent <= 0.1. if it was percent >= 0.0 && percent < 0.1, it would be easier.

→ More replies (10)
→ More replies (23)

167

u/mikebalzich Jan 18 '23

y'all mfs need case statements

323

u/DagothHertil Jan 18 '23

Lemme just do a switch for every possible double value in the range 0.0 and 1.0, be right back

→ More replies (27)
→ More replies (10)

4

u/tadlrs Jan 18 '23

It is not the length that matters. It is the effort. I've been told.

→ More replies (2)

34

u/[deleted] Jan 18 '23

[removed] — view removed comment

99

u/aehooo Jan 18 '23

So, while I agree with the loop strategy, the more I look at the original solution, the more I am fine with it (at least in Java, but I know the code is C#). With a loop*, it would create a new string every time plus the append it, creating another new string if you don’t use StringBuilder. But this isn’t a problem where you have to generate a lot of different strings, you already know beforehand that you have 11 options you should return, therefore this is better memory wise.

Could the code be better? Probably. But I think it’s fine when you put in context.

Edit: *unless it’s an array with 11 strings and you are looping through it

→ More replies (18)
→ More replies (13)

5.1k

u/Miles_Adamson Jan 18 '23

> Sees code is 20 lines instead of 4

> Writes 78 lines of text on reddit, github and slack to complain about it

573

u/Kimorin Jan 18 '23

Proceeds to say: this is why comments are important

141

u/Zomby2D Jan 18 '23

No one said the comments had to be in the code. Reddit comments are just as valid.

→ More replies (7)

511

u/TheBirminghamBear Jan 18 '23

Elon Musk approves of your salient code.

86

u/[deleted] Jan 18 '23

Let's delete half of it and see if it still works? Shrug, Elon did it so we gotta do it too

→ More replies (2)

34

u/GhostCheese Jan 18 '23 edited Jan 19 '23

String r = ""; For ( int i = 0; i < 10; ++i ){ If (int(10 * percentage) >= I ) concatenate(r, "●") Else concatenate(r,"○"):} Return r;

16

u/Thin-Limit7697 Jan 19 '23 edited Jan 19 '23

At least put some spaces at the left to indent it.

string r = "";
for ( int i = 0; i < 10; ++i ) {
  if (int(10 * percentage) >= i ) concatenate(r, "●")
  else concatenate(r, "○");
}
return r;
→ More replies (9)
→ More replies (7)

35

u/[deleted] Jan 18 '23

I honestly don't know what it is about programmers and ego. It's like the field is basically a giant dick measuring contest. Honestly kind of hate it and I've been in this bish for 20 years.

7

u/madallday Jan 19 '23

I somehow subscribed to r/ProgrammerDrama ?

→ More replies (3)

3

u/RockleyBob Jan 18 '23

For real though, I hope whoever wrote that is taking the ribbing in stride.

I can't imagine what you savages would do to some of my shit code if you got a hold of it.

→ More replies (1)

91

u/[deleted] Jan 18 '23

[removed] — view removed comment

146

u/[deleted] Jan 18 '23

After thousands of reviews asking “what does this thing do again?” I opted out for the verbose, absolutely dumb code that needs no explaining.

→ More replies (9)

18

u/aehooo Jan 18 '23

Wouldn’t it be 11 strings? I am just trying to understand your logic, no criticism.

→ More replies (3)
→ More replies (4)
→ More replies (6)

2.2k

u/controwler Jan 18 '23

Hey I live in the Netherlands and of course use DigiD, never had issues with it so if it works I'm not hating. For a public sector application it's actually quite impressive

769

u/thanatica Jan 18 '23

Open source apps in the public sector is quite a feat to begin with. This was unthinkable even 10 years ago. Many governments could learn from this.

130

u/Daniel15 Jan 18 '23

It makes sense... If taxpayers are paying for the development, taxpayers should be able to see what they've paid for.

→ More replies (16)

262

u/shekurika Jan 18 '23

there are efforts in some european countries (germany, switzerland, netherlands) to force the government to open source all projects it pays for with edception only when its needed for security (like military stuff)

→ More replies (32)

19

u/snugglezone Jan 18 '23

NASA has an open source policy. All of my work there was available on github.

→ More replies (1)
→ More replies (8)

111

u/BruhMomentConfirmed Jan 18 '23

There's a super low max amount of people that can use DigiD at once though, which I find super weird.

20

u/ramblinroger Jan 18 '23

I guess it just isn't necessary? Of course no way to be absolutely sure it never will be, but probably inefficient to always have that capacity

→ More replies (3)
→ More replies (1)
→ More replies (58)

2

u/thanatica Jan 18 '23

I don't see it linked in the comments, so here is the original piece of code:

https://github.com/MinBZK/woo-besluit-broncode-digid-app/blob/ad2737c4a039d5ca76633b81e9d4f3f9370549e4/Source/DigiD.iOS/Services/NFCService.cs

Honestly, a screenshot of a tweet is bad enough, but a screenshot of a screenshot reeks of disinformation. In this case however, it is genuine.

→ More replies (1)

2

u/lotj Jan 19 '23

Top one works, can be debugged by sight, and any changes is literally irrelevant due to how simple the call is and any practical use-case. I’d totally pass it in a code review.

1

u/ohsangwho Jan 19 '23

yeah I mean I saw the top one and laughed but also I laugh every time I write code like this. I know people don't like it and I myself feel like its not... clean, ig, that's why I laugh about it, but its just so straightforward and hard to mess up and anything that decreases the amount of debugging I do is a godsend tbh.

2

u/djkevinha90 Jan 19 '23

Noobie here, Im confused, isn't the top part cleaner code....?

2

u/ohsangwho Jan 19 '23

yes, the joke is how bad it is

people dislike the kind of code that the top one is because it uses needlessly many if statements. As a joke they put more unnecessary if statements and converted it to binary search which is such overkill.

The joke is how bad and needlessly complicated it is, and that they said they fixed it by making it worse.

2

u/djkevinha90 Jan 20 '23

Oh ok, thanks so much for answering. so what would actual good code look like? To be fair, I get that there's a lot of if statements but it would probably something i would write. It's simple and anyone can understand what's going on with a glance. And I'm guessing it's like some sort of loading or chart notation so it's not like it needs to be super fast, right?

2

u/ohsangwho Jan 20 '23

this is faster than most implementations, its O(1). Theres just much less wordy ways to do this involving a for loop, or a lot of people in the comments have been doing some clever things with substrings, I could link if you want.

Tbh - the code is fine. It is very readable. I code like this all the time and always go "lmao this is so bad" but it is very readable and hard to get wrong. Anything that decreases how long it takes for me to debug, I like. I think other people do the same, write a series of if statements, think "lmao this code sucks" but keep doing it because there's really nothing wrong with it, it just looks kinda gross. To me part of why it was funny is because I do it all the time.

Though if I were writing like a program for the government, I'd probably use the if-statements so as to not give myself any unnecessary headaches when initially coding, and then refactor later so it looks more polished. I think ppl think that with govt code someone would've refactored it to look better.

→ More replies (1)

267

u/DarthNihilus1 Jan 18 '23

redditors try not to see any code snippet as an optimization challenge [IMPOSSIBLE]

43

u/Crypt0n0ob Jan 19 '23

I seriously don’t get it what’s the issue here. Sure, I can replicate same functionality in 3-4 lines, but I’m sure whoever developed this, they could too.

I think goal was that to make it more readable and easy to understand and unlike my 3 liner, this is perfectly readable and you can understand what it does moment you look at it instead of spending time analyzing what my 3 liner does.

→ More replies (11)

23

u/[deleted] Jan 18 '23

You misspelled obfuscation lmaooo

→ More replies (1)

2.2k

u/alexgraef Jan 18 '23 edited Jan 18 '23

The amount number of people in this comment section suggesting to solve it with a for-loop shows that both the original code and the revised version are on average better than what this sub has to offer.

Here's my take on it.

260

u/[deleted] Jan 18 '23

Then sadly the og version is still faster because the compiler does black magic and things no mortal can understand.

140

u/alexgraef Jan 18 '23

In this case not really. "switch" gets transformed to hash table lookups sometimes, but this isn't even possible here. And as percentages will be equally distributed for progress, you can't even do much branch prediction. My version is certainly faster.

→ More replies (6)
→ More replies (13)

41

u/GrinningPariah Jan 18 '23

This is such a great example of the notion that good code is "transparent" and lets you see other parts of the problem or the systems around it.

Your first solution is how I'd do it, within the bounds of this problem. But seeing it written out made me realize... why the fuck is this is a string anyways? These dots should be like CSS elements or something. This is a UI component.

→ More replies (3)

51

u/danishjuggler21 Jan 18 '23

People round here like to “open their mouths and remove all doubt” of their stupidity.

→ More replies (3)

9

u/[deleted] Jan 18 '23 edited Jan 18 '23

If the "problem" is too many conditional statements, loops aren't going to solve it. When the code is compiled, conditionals will be added for each iteration to determine whether or not to execute the next iteration of the loop, this is the reason why programs that need to be performant or real time use a technique known as "loop unrolling".

If the "problem" is that it doesn't look "elegant" then I'd agree.

Then again, if the code functions according to the business requirements, then is there really a problem? People to are too quick to critique others work only to inflate their own ego.

→ More replies (2)

4

u/[deleted] Jan 18 '23

I need to impress Mr Musk, so the more lines of code the better.

Your solution is far too compact and shows a lack of skill as a potential twitter programmer.

→ More replies (1)

3

u/Fig1024 Jan 18 '23 edited Jan 18 '23

I would convert the float range to integer first, like

int num = (int)(percentage * 10.0 + 1.0);

It gets you 1-10 range, so you don't need to do range comparison. You still have to add special case for 0. Simplest would be a switch statement

EDIT: you can do without for loops by assigning text buffer to full 10 circles and using the 'num + 1' integer as index into string to set that character to NULL. That way string gets cut off at right point, no for loops or multiple comparisons . Something like:

return "xxxxxxxxxxx".Truncate(num);
→ More replies (3)
→ More replies (115)

3.0k

u/AlbaTejas Jan 18 '23

The point is performance is irrelevant here, and the code is very clean and readable.

2.7k

u/[deleted] Jan 18 '23

The performance isn't even bad, this is a O(1) function that has a worst case of a small number of operations and a best case of 1/10th that. This is fast, clean, easy to read, easy to test, and the only possibility of error is in the number values that were entered or maybe skipping a possibility. All of which would be caught in a test. But it's a write-once never touch again method.

Hot take: this is exactly what this should look like and other suggestions would just make it less readable, more prone to error, or less efficient.

801

u/firmalor Jan 18 '23

The more I look at it, the more I'm inclined to agree.

→ More replies (47)

137

u/DHH2005 Jan 18 '23

You see a lot of people criticizing it, without giving their hypothetically better answer.

→ More replies (88)

34

u/enfly Jan 18 '23

I ❤️ you. I hope one day we get to work together. Maybe I won't get urges to bang my head against the wall during code reviews.

38

u/AlbaTejas Jan 18 '23

Personally I'd calculste length and substring but that's habitual from being a performance weenie dealing with loops that run billions or trillions of times per job.

CDIR$VECTOR ftw

→ More replies (1)

107

u/K_Kingfisher Jan 18 '23 edited Jan 18 '23

Exactly.

The amount of people who don't understand time complexity is too damn high.

Unless I missed some if statements in there, the original runs in O(10) and the new one in O(4) - and not O(log n) as claimed . Asymptotically, they both run in O(1). Which is constant time.

Neither one is better than the other in performance. The second method is just harder to read.

Edit: A binary search is O(log n) for an arbitrary n number of elements. Here, the elements are always 10 (the number 1 split in tenths). Log 10 = 3.3, so it's always O(4) because it's always O(log 10).

Always the same number of steps for the worst possible case, means constant time.

→ More replies (37)

98

u/Free-Database-9917 Jan 18 '23

if (percentage == 0) {

...

}

else if (percentage <= 0.1) {

etc.

This is as readable, less prone to error, and more efficient

→ More replies (36)
→ More replies (79)

356

u/RichCorinthian Jan 18 '23

Most of the people making fun of this are junior devs who pride themselves on writing incomprehensible one-liners that they themselves will struggle to understand in a week.

128

u/xkufix Jan 18 '23 edited Jan 18 '23

People creating config files for this and abstracting away without need are just building a variant of enterprise fizzbuzz (https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition).

Sometimes ten blue dots are good enough. Not everything needs a ProgressBarFactory with an ItemCountBuilder, an ItemColorConfig and a mocking framework to test it just for the business to tell you that they want a spinner.

→ More replies (8)
→ More replies (5)

154

u/samanime Jan 18 '23

Yeah. It's funny how people are so fixated on this bit. It isn't the most elegant solution, but it really isn't bad, and the readability is excellent. I'd accept this in a PR.

21

u/Electronic-Bat-1830 Jan 18 '23

We were just kinda competing with each other here. I mean, don't get me wrong, if I were to see that code, I would merge it, no problem. It gets the job done.

Maybe I would be more paranoid and pay closer attention if I were developing a time critical piece of software, but I don't know how an authenticator app would fit into that scenario. But if anyone does work in one of those apps and think I am wrong, feel free to shout yourselves out in the replies.

→ More replies (2)
→ More replies (4)

31

u/sicsche Jan 18 '23

It is so readable that even someone who can't code (ie myself) exactly understand what each line of code does and how it functions.

58

u/AdDear5411 Jan 18 '23

Too many people overengineer just because they can

→ More replies (1)

36

u/alexgraef Jan 18 '23

Well, you could put the ten strings into an array, and then take the percentage, multiply by ten, round, and use that as an index into said array.

I doubt it would make readability worse, and it would forego all branching.

0

u/[deleted] Jan 18 '23

[deleted]

→ More replies (6)

17

u/DimBulb567 Jan 18 '23

Yeah, it's clean and readable, but I think you could easily just write code to add blue circles up to the percent using a for loop and then pad with white circles. Still clean and readable, but in less code. Then again I'm no professional so I could be wrong.

→ More replies (1)

3

u/10BillionDreams Jan 18 '23

"actually 12 dots looks better, not 10"

Being simple and understandable isn't enough, clean code should be easy to make changes to.

→ More replies (48)

103

u/DangyDanger Jan 18 '23

And now goes a series of posts one upping each other. Next one will use StringBuilder and ReadOnlySpan<char>, just wait.

22

u/argv_minus_one Jan 18 '23

Anything involving a heap allocation is most certainly not going to be faster than this function.

→ More replies (9)
→ More replies (1)

142

u/coolbeaNs92 Jan 18 '23

I'm not a dev, but why is the first a problem? It's super readable that even dumb Sysadmins like myself can understand easily what is happening.

This can't be such a strenuous statement that performance would be an issue, would it?

137

u/wheresthewhale1 Jan 18 '23

You're right, there's literally nothing wrong with it. Sure you could make it a bit faster but this absolutely is nowhere near performance sensitive. What is rather funny/depressing is seeing a lot of people post their own "smarter" solutions which are actually far slower and less readable

45

u/anto2554 Jan 19 '23

Can you implement it on the blockchain

→ More replies (3)

15

u/1AMA-CAT-AMA Jan 19 '23

Its the product of code interviews wanting the most optimized leet code one liner rather than usable readable code that will be understandable when someone else looks back at the code in 10 years.

→ More replies (1)
→ More replies (6)

13

u/OneLostOstrich Jan 19 '23

There actually isn't anything wrong with it. It's pretty crude though, but it works and will continue to work just fine. It's just that if your entire program is filled with code like this, you're doing really cheesy programming.

→ More replies (1)

5

u/Coding-Kitten Jan 19 '23

For me at least, & I'd imagine for many others as well, there are some patterns that instinctively jump out as "BAD" that must be fixed. Two of them being long if chains, & using if repetitively to do the same thing but with different values.

Now in practice, there is actually nothing bad with the code. It does what it needs to do, it's very readable in what it's trying to do & it doesn't do 900 allocations or take five hours to do so.

But I can easily see how for many people the monkey brain side of them just instinctively goes "IF CHAIN BAD, USE ONE LOOP INSTEAD OF 10 IFS".

→ More replies (12)

471

u/Badgermanfearless Jan 18 '23

Chaotic evil

55

u/trevdak2 Jan 18 '23 edited Jan 18 '23

I think that would be chaotic good. Chaotic evil would be making it very subtly incorrect, like replace all the <= with <

→ More replies (2)

10

u/jldez Jan 18 '23

Don't say that, WotC will come for you

214

u/lukkasz323 Jan 18 '23

The first code might seem stupid, but it's extremely readable and bug-proof.

→ More replies (39)

71

u/RakhAltul Jan 18 '23

How to outsource coding easily Step 1: post code on internet Step 2: take best solution Step 3: profit

26

u/JoesusTBF Jan 18 '23

Step 2.5: Know how to determine which solution is "best"

→ More replies (3)

3

u/[deleted] Jan 18 '23

that just describes stackexchange

→ More replies (1)

60

u/[deleted] Jan 18 '23

The real humor is in the comments

46

u/ISnortSilicon Jan 18 '23

This is solution is fine. Why make a complex solution to a UI feature that servers as fluff?

→ More replies (3)

213

u/throwaway_mpq_fan Jan 18 '23

you could eliminate a lot of return keywords by using kotlin

that wouldn't make the code better, just shorter

65

u/Electronic-Bat-1830 Jan 18 '23

Can't you already determine how many dots you need to show by multiplying the percentage with 10 and using a for loop?

121

u/Krowk Jan 18 '23 edited Jan 18 '23

No loops needed: (in python because I'm trying to forget how to code in java)

def f(percent):
    full = '🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵'
    empty = '⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪'
    return full[:percent//10] + empty[:(100-percent)//10]

Or something like that, i'm on my phone can test if this implemention works but the idea of it can be done.

→ More replies (55)

8

u/Torebbjorn Jan 18 '23

Yeah, you COULD create a whole new string every time the function is called, and that would be less code

But for something like this, it is definitely better to have all the possible strings stored in static memory.

But it could instead just have them in an array, and get the index from multiplying by 10 as you say

→ More replies (2)

30

u/AlternativeAardvark6 Jan 18 '23

I think they prioritize readability, as they should.

→ More replies (143)
→ More replies (11)

38

u/V0ldek Jan 18 '23

You don't need Kotlin to eliminate returns.

private static string GetPercentageRounds(double percentage) => percentage switch
{
    0      => "⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪",
    <= 0.1 => "⚪⚪⚪⚪⚪⚪⚪⚪⚪🔵",
    <= 0.2 => "⚪⚪⚪⚪⚪⚪⚪⚪🔵🔵",
    <= 0.3 => "⚪⚪⚪⚪⚪⚪⚪🔵🔵🔵",
    <= 0.4 => "⚪⚪⚪⚪⚪⚪🔵🔵🔵🔵",
    <= 0.5 => "⚪⚪⚪⚪⚪🔵🔵🔵🔵🔵",
    <= 0.6 => "⚪⚪⚪⚪🔵🔵🔵🔵🔵🔵",
    <= 0.7 => "⚪⚪⚪🔵🔵🔵🔵🔵🔵🔵",
    <= 0.8 => "⚪⚪🔵🔵🔵🔵🔵🔵🔵🔵",
    <= 0.9 => "⚪🔵🔵🔵🔵🔵🔵🔵🔵🔵",
    > 0.9  => "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵",
};

I'd argue it's shorter and more readable.

24

u/alexgraef Jan 18 '23

Looking at it again, it is shorter, more readable, and certainly wrong. But only because the alignment of the filled dots is wrong...

→ More replies (3)
→ More replies (2)
→ More replies (2)

28

u/Naive_Age_566 Jan 18 '23

does it work?

is it fast enough?

is it secure enough?

you don't get paid for beautiful code. you get paid for solutions for problems.

→ More replies (1)

107

u/capi1500 Jan 18 '23

It's still O(1) time, as number of cases is constant... The second one's still faster obviously

101

u/[deleted] Jan 18 '23

Might not be faster because the compiler might be able to optimize the first version better then the 2nd.

Dev or ~60 years of compiler development?

32

u/capi1500 Jan 18 '23

Now I'm actually curious how both pieces compile

→ More replies (3)

8

u/alexgraef Jan 18 '23

I am certain there is little optimization potential with both version from the compiler. Can't do any lookups with that kind of if-clauses, and no particular branch prediction. It is going to run through every comparison and branch where true.

→ More replies (3)

115

u/[deleted] Jan 18 '23

The second one's still faster obviously

never make an assumption about performance ever.

35

u/ProperApe Jan 18 '23

Making an assumption is fine, but you should verify if it holds.

→ More replies (2)
→ More replies (3)

46

u/pk436 Jan 18 '23

What's wrong with the first code exactly? It's clear and readable.

23

u/ProgramTheWorld Jan 18 '23

Nothing wrong with it. It’s often more preferable than “clever” solutions. Easy to understand and less prone to bugs. Leave the cleverness for code golfs, not consumer facing products.

→ More replies (10)

10

u/stamminator Jan 18 '23

Finally, C# gets some recognition!

*sees post*

😐

→ More replies (1)

9

u/mynewromantica Jan 18 '23

If this is the worst code in the app then it’s probably in pretty good hands.

8

u/NiteShdw Jan 18 '23

Wait … this is all too complicated. Just multiply by 10 and pad the rest of the string.

→ More replies (1)

32

u/Infamous-Date-355 Jan 18 '23

Now all these wise guys gonna give you a quicker faster solution

16

u/pako_adrian Jan 18 '23 edited Jan 18 '23

It was probably some poor intern who wrote this and they're getting bashed on Reddit :/

(in a positive way for the intern - seeing as people might be misunderstanding my comment!).

71

u/[deleted] Jan 18 '23

Poor intern wrote readable code to do something where performance is a non-factor. I'd call that a job well done.

→ More replies (2)
→ More replies (1)
→ More replies (5)

18

u/RHess19 Jan 18 '23

Why people care so much about the performance of this code is beyond me. As others have mentioned, its already O(1). Even if you could speed it up slightly, who cares? It's not like improving the efficiency of this will create any meaningful speed increase since the animation is probably done in a matter of seconds anyways.

8

u/wouldacouldashoulda Jan 18 '23

Performance is easy to measure and code quality is not. If code quality was easier to express as a number the human race would have ascended by now. Instead we are obsessing about the performance of a string builder in a garbage collected language running on a phone.

3

u/ubelmann Jan 18 '23

Yeah, if your loading bar loads so quickly that the performance of this function matters, then you have completely wasted your time even creating a loading bar, because no one will ever see it.

6

u/[deleted] Jan 18 '23

It is with great glee that I wish to announce this code is good. It's great. As a matter of fact, it's so great I don't think we'll ever need to touch it again -- and to prove my point, I will proceed to refuse to ever take even the slightest glance at it for the rest of eternity.

15

u/cmaciver Jan 18 '23

Idk man i just say use a map or a dictionary or whatever you wanna call it, just multiply percentage by 10 and round it up

21

u/kernel_task Jan 18 '23

To be fair, even if you wrote it originally with loops, a really smart optimizing compiler would likely rewrite your code in exactly this way.

25

u/alexgraef Jan 18 '23

That's because you are not supposed to use a fucking for-loop for this simple problem. You just concatenate the correct amount of non-filled circles to the correct amount of filled circles. It is very simple math.

21

u/kernel_task Jan 18 '23

… how do you think computers concatenate a variable number of strings?

→ More replies (4)
→ More replies (20)

14

u/djingo_dango Jan 18 '23

My takeaway from this is it’s really telling how many people think a simple for-loop is over-engineering.

This code works because the requirement is pretty simple and copy pasting the same line 10 times is a easy way of achieving what you want. But this is violating a very basic software engineering principle, DRY. So if you’re learning to code try not to follow what has been done in this code.

Let me just state a very hypothetical scenario where you’d need to unnecessarily modify a lot of code. Say the Dutch government says that blue is not really a color-blind friendly color so they should be using a different color for the progress dots. Now you have to basically replace 55 blue dots to something else. But if you used a different technique you’d have to change one single character to achieve this.

But of course it all depends on the requirement at hand. That’s why understanding what’s required is way more important than the actual code. This simple copy pasted solution works here because that’s what’s required.

5

u/nickbeth00 Jan 19 '23

I can't believe I had to scroll this far to find someone that actually said this.

→ More replies (1)

5

u/-non-existance- Jan 18 '23

Okay I feel really stupid, why is the first code even a problem? Like, why was it tweet-worthy to begin with? It's not fancy or perfectly efficient by any stretch but it works and minimizes the check to at most 10-11 operations. A check that runs, how many times? I'm not familiar with the app in question.

3

u/[deleted] Jan 18 '23

The humor is the response, which is why it's included in the image.

3

u/[deleted] Jan 18 '23

To me it’s not a problem, its just the comments saying its easy to tweak, when it’s not.

If you can be guaranteed to only show those 11 progress bars, it’s fine.

9

u/[deleted] Jan 18 '23

The only thing that bothers me about the code is that negative values gives back a full line of blue circles.

Ther than that it implements the KISS (Keep it simple, stupid) theorem very well.

It's not about flexing with your code abilities...

→ More replies (1)

8

u/[deleted] Jan 18 '23

The first one is lovely code! The way I would implement it would be slightly different at first glance, but that way is more readable anyway. I was thinking something like

blues = trunc(percent*10)
whites = 10-blues;
return repeat("🔵",blues)+repeat("⚪️",whites)

but that’s less readable 😅

eta: typo

→ More replies (3)

4

u/[deleted] Jan 18 '23

It's a silly solution, but it's not going to be very slow tbh.

12

u/argv_minus_one Jan 18 '23

It's significantly faster than a lot of the other proposals I'm seeing in this thread, many of which involve allocating a new string.

→ More replies (6)

4

u/oddspellingofPhreid Jan 18 '23

Code has 10 if statements.

"Too many if statements!"

Code has 10 if statements.

4

u/anengineerandacat Jan 19 '23

Top version is clean and easy to understand... not ideal perhaps but it's I am assuming functional.

Bottom version is a cluster fuck, don't care if it's faster as the top is readable and the bottom is something I don't want to read.

Better solution is to just shove all the values into an array and use the percentage as an index which then it just becomes a simple lookup after you take the percentage and multiply it by 10 and truncate it.

If you wanted to be extra cautious... min/max the values so they don't go outside of an expected range.

4

u/cmilkau Jan 19 '23

if that's the fix, i want the problem back.

10

u/[deleted] Jan 18 '23

Why not just throw the 11 options in an array and find the string at index percentage*10? You'd have your readability without a dozen if statements?

7

u/Wherethefuckyoufrom Jan 18 '23

Array can go out of bounds, might need a test.

→ More replies (1)
→ More replies (2)

6

u/P0pu1arBr0ws3r Jan 18 '23

Smh everyone knows it's fastest to use a single return statement and 10 ternary operators. Something like cafes and tail end function or cps or something.

(Cafes/environments, cps and tail end recursion are PLC concepts [hmm programming language concepts concepts] not exactly supported in c#, at least tail end recursion isn't optimized in c#)

6

u/[deleted] Jan 18 '23

Erm…multiply by ten and use math ceiling to add that number of strings together for the result. Then pad right for ten characters with the other character. Job done. 🤣

3

u/eugene20 Jan 18 '23

No-one going to talk about why the heck is it returning unicode at all instead of leaving that to the front end? Or is this normal for iOS ?

→ More replies (1)

3

u/SirMooserson Jan 18 '23

I've been programming for 12+ years but I have to ask...wtf and how tf are these circles being returned? Everyone acting like this is normal and I've never seen this shit in my life. Feel like I'm out of the loop. Also, nothing wrong with the original solution

→ More replies (2)

3

u/Apocalypse_Fudgeball Jan 18 '23

Here's an honest question coming from someone who only knows a some Python and JS: How fast would it be to do the following using an equivalent C syntax?

if percentage >= 1:
    return 10*"🔵"
else:
    return ceil(10*percentage)*"🔵" + ceil(10*(1 - percentage))*"⚪"
→ More replies (1)

3

u/brooklyn-man Jan 18 '23

This is gross

3

u/goodnewsjimdotcom Jan 18 '23

I think it could be optimizfuscated more if you try.

3

u/[deleted] Jan 19 '23

Isn’t life just one big if statement when you really think about it?

3

u/thedragonturtle Jan 19 '23

People talking about efficiencies are ignoring any potential info about the input datasets.

If this percentage parameter represents % complete and 95% of users are at 0% then this function is incredibly efficient.

But over time, this function will slow down as people complete whatever it is.

3

u/richardathome Jan 19 '23

return substr("**********0000000000", 10-n*10, 10);

pseudocode. but you get the idea.

returns an 10 char string starting at position 10-n*10

→ More replies (3)

3

u/syko82 Jan 19 '23 edited Jan 19 '23

At least this takes the same amount of time every time. Wasteful of time, but it's small.

private static string GetPercentageRounds(double percentage){
    static string off = "⚪";
    static string on = "🔵";
    string output = "";
    for(int x=0; x<10; x++){
        output += Math.Floor((percentage*10)-x) > 0 ? on : off;
    }
    return output;
}
→ More replies (1)

3

u/KIFulgore Jan 19 '23

No problem here. The code is straight forward, easy to read, and not time-critical. Renders with emoji, so no need for additional art assets. And it will render with wrapping, if needed, or easily scale to the device's resolution, font, and magnification settings.

There are reasons why font-based iconography like font-awesome is popular. Unicode standard characters are more universal still.

7

u/Ferro_Giconi Jan 18 '23

I really don't see what's wrong with that original code. It's extremely easy to understand at a glance and probably doesn't run 100 times per second so who cares if it's not optimized to be 10% faster than it currently is?

5

u/_dictatorish_ Jan 18 '23

In python I'd just do something like

num = ceil(percentage*10)

return 🔵num + ⚪(10-num)

Maybe add an if statement for if num>10

→ More replies (2)

5

u/LieutenantNitwit Jan 18 '23

I dunno. Pretty much everyone on the internet with functioning eye holes can sus out what this is doing, so props for readability?

10

u/mikeyj777 Jan 18 '23

This is what happens when you take algos and data structures but never worked on an actual project.

12

u/argv_minus_one Jan 18 '23

If you took algos and data structures, you'd surely know that it'd be faster to stuff the strings into an array and use the input value as an array index.

→ More replies (1)

4

u/djingo_dango Jan 18 '23

If you took algo and data structure you’d change your mind after you’ve pasted the same line 3 times

→ More replies (1)

8

u/SteelMarch Jan 18 '23

Jeez the people on this subreddit focus too much on optimization rather than readability its kind of depressing that this is all leetcode has taught people instead of basic software design principles.

3

u/mrjackspade Jan 18 '23

I was working with a guy doing a leetcode thing, and I wrote up a function and then sent him a second validation function.

He looked at the validation function and was like, "What's this?" So I told him "well that's how I would actually write it if I was checking it in and not trying to beat an optimizer."

His response was something along the lines of "holy fuck, leetcode is worthless"

The second function was like 10% as long and the intent was incredibly obvious because it wasn't microtimized.

→ More replies (2)

4

u/bikki420 Jan 18 '23 edited Jan 18 '23

Just do what's essentially a bounded lerp to convert the percentage to an index and use a look-up table. This is C++ code, but still:

#include <algorithm>

[[nodiscard]] auto constexpr
get_progress_bar( float percentage ) noexcept {
   static char constexpr const* lut[] {
      "⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪",
      "🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪",
      "🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪",
      "🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪",
      "🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪",
      "🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪",
      "🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪",
      "🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪",
      "🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪",
      "🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪",
      "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵",
   };
   static auto constexpr min{ 0.0f }, max{ 10.0f };
   std::size_t const index = std::clamp( percentage * max, min, max );
   return lut[index];
}

edit:

In case anyone is wondering why I didn't just use literals instead of min and max, it's because std::clamp returns by reference; which means that if it hits either bound when the provided bounds are temporaries, that results in a dangling reference result which of course is no bueno.

4

u/tinusxxl Jan 18 '23

why’s everyone bitching on a progress bar lol. yes there’s more efficient ways but this one’s literally only shown once when you get the nfc scan pop-up while scanning your passport/id

5

u/wordsoup Jan 18 '23

Being a software engineer for 12 years, I think this is actually not bad code.

4

u/mendrique2 Jan 18 '23

imagine they want to have 5% steps in the future, you have to touch 10 Ifs and add 10 more, the chance of doing a typo somewhere is immense. Code being understood by the lousiest layman on the team is not necessarily a good thing.

2

u/3RaccoonsInAManSuit Jan 18 '23

Lol. It’s always a surprise for me to find out other people use C# as work as well.

2

u/palomdude Jan 18 '23

Implementing binary search my ass. They just said that to sound more impressive.

→ More replies (1)

2

u/HaDeS_Monsta Jan 18 '23

Why always the

If > 0.5

If it would be smaller there would've been a a return already

2

u/firowind Jan 18 '23

All this can be solved with a simple modulos operator

2

u/Sultan75 Jan 18 '23

i absolutely undeniably love it

2

u/slayemin Jan 18 '23

haha, thats much worse…

2

u/[deleted] Jan 18 '23

First pic is what a college student and a junior engineer would write. Second pic is something a l2-4 engineer will write. We need a gray wizard to write the actual code.

→ More replies (1)

2

u/Phoenix7501 Jan 18 '23

My brain cells r dying

2

u/Ronaldarndt Jan 18 '23
private static string GetPercentageRounds(double percentage)
{
    var blueCount = (int)(percentage * 10);
    return new string('🔵', blueCount) + new string('⚪', 10 - blueCount);
}

2

u/Slippedhal0 Jan 18 '23 edited Jan 19 '23
private static string GetPercentageRounds(double percentage)
{
    int roundsCount = (int)Math.Ceiling(percentage * 10.0)
    return new string("🔵", roundsCount) + new string("⚪", 10 - roundsCount);
}

2

u/andrewsutton Jan 19 '23

I feel like everyone commenting has completely missed the fact that the function accepts, but does not correctly address, negative numbers as inputs.

You're all looking at style and missing substance.

2

u/sontaj Jan 19 '23

There's two things I can't stand in this world: People who are intolerant of other people's cultures, and the Dutch.

2

u/ConsciousAntelope Jan 19 '23

Too many if statements

Provides solution with the same number of if statements 💀

2

u/qcihdtm Jan 19 '23

The code needs to be correct, secure, performant, readable, maintainable and reusable.

Correct: It is correct. It does the job.

Secure: Can’t tell whether the input is validated somewhere else or not. If it is, this is secure. If it is not, it should be.

Performant: we could maybe shave a few CPU cycles with else statements and some comparative logic reordering to account for the most common scenarios first. But, not much more efficient than a fixed number of literals.

Readable: perfection.

Maintainable: hm… changes are gonna be a very repetitive task.

Reusable: well… the code is very specific so it can only be reused in ver specific cases.

Not everything needs to be a clever solution to a problem. Sometimes a good basic and simple solution is exactly what the problem needs.

2

u/AlwaysHopelesslyLost Jan 19 '23

Unironically this is how 80% of the code in the legacy code base my team maintains at work is setup. It is God awful.

We have a bit that is integral to issuing payments. The logic that determines where the money comes from looks like this. Except every one is a database call that is slightly different and there are a handful of random null checks.

There are SO many ways you can end up anywhere

2

u/genkidame6 Jan 19 '23

From O(1) to O(log1)

2

u/SwivelChairSailor Jan 19 '23

The original code is better than most comments because it's understandable and maintainable by anyone with even zero experience, was written using ctrl+c ctrl+v, and likely cost less to write. If I hired a dev who spent even the slightest bit of extra time overthinking this, I would not be happy. Copy paste some circles and move on.

→ More replies (1)

2

u/moschles Jan 19 '23 edited Jan 19 '23
def progress_bar(c):
  b=int(10.0*c)
  return( ('🔵'*b) + ('⚪'*(10-b)) )

print([ (pc,progress_bar(pc)) for pc in [0.13,0.9,1.0] ])

2

u/kruegefn Jan 19 '23

Still the same number of IFs.

Still can't deal with negative values properly.

Still using double.

Semantics changed when the value is zero.

2

u/dbel12 Jan 19 '23

So I’ve been thinking, and though their solution seems funny I haven’t really seen a better one. Would any of you guys be willing to share a better solution with me? I was thinking something along the lines of:

private static string GetPercentageRounds(double percentage){

  this.percentage = percentage * 10; 
  string str1 = “”;
  for(int i =0; i <= this.percentage; i++){
        str1[i] = “🔵”;
  }
  str1.PadLeft((10 - this.percentage), ‘⚪️’);

  return str1;

}

Pardon the formatting and such, I did this on my phone and don’t often code in C#. It’s silly but y’all’s thoughts would be appreciated! God bless y’all!

2

u/rainshifter Jan 19 '23 edited Jan 19 '23

private static string GetPercentageRounds(double percentage)
{
    int numBlues = (int)Math.Ceiling(percentage * 10);
    int numWhites = 10 - numBlues;
    string result = "";
    for (int i = 0; i < numBlues; i++)
    {
        result += "🔵";
    }
    for (int i = 0; i < numWhites; i++)
    {
        result += "⚪";
    }
    return result;
}

2

u/RallyPointAlpha Jan 19 '23

Saw the original post the other day and felt like a bad developer because it looked like somehow I would write.

I feel much better today after reading the comments!

3

u/euph-_-oric Jan 18 '23

So u don't code in c# , but what freaks me out isn't the if statements , but is it common practice to return strings like this for ui elements?

→ More replies (1)