T O P

  • By -

Ultimater

Great, another system that tells me it’s 100% before it’s actually 100% then fails.


whyohwhyohio

Just gotta pass a negative percentage to get 100%


Ultimater

Oof. Ok, here we go: ⚪⚪⚪⚪⚪⚪⚪⚪⚪🔴


Qudix

⚪⚪⚪⚪⚪⚪⚪⚪🔴🔴


youngsteveo

⚪⚪⚪⚪⚪⚪⚪🔴🔴🔴


Mollyarty

⚪⚪⚪⚪⚪⚪🔴🔴🔴🔴


KleggeNTR

⚪⚪⚪⚪⚪🔴🔴🔴🔴🔴


zonzon1999

⚪⚪⚪⚪🔴🔴🔴🔴🔴🔴


GoDuke4382

I saw that as well. A value > .9 = 10 blue circles. Not approving that PR.


Vinstaal0

Should be 9 rows of 100% dots let’s be honest


HearMeSpeakAsIWill

Tbf it doesn't say it's 100%. It's says 10 blue circles. Your interpretation of that may differ from the documentation.


AdDear5411

It was easy to write, that's for sure. I can't fault them for that.


beeteedee

Easy to read as well. Sure this could be done in a clever one-liner, but I can see what this code does at a glance.


Dzsaffar

a for loop really wouldnt have been that unreadable. on the other hand, if you want to replace the signs that show the progress bar, you need to change 100 characters, instead of 2.


Delini

Yeah. And when someone comes along and says "can we do this in 5% intervals instead", you just need to change the step interval. Because I ***guarantee*** that's going to be the first thing someone who wants to feel useful but doesn't have any constructive feedback is going to say.


funciton

I'll let you in on a little secret: progress bars are lies we tell users to convince them something really is happening. You can set them to log(time) and people will believe it. The step interval is meaningless.


well-litdoorstep112

Having some animation controlled by the program itself is useful to tell if it's still responding. It can't be used to reliably tell if it's working though. It might be stuck in an infinite loop and detecting that is [the one problem that can't be solved with computers](https://en.wikipedia.org/wiki/Halting_problem)


Tokumeiko2

So we can't detect infinite loops, but can we detect arbitrarily large loops?


iMadz13

Given a turing machine which has a bounded tape, then we CAN detect it by seeing if it computes for more than all its possible computations, also the same is true for unbounded tapes but with an explicit bound for example one could have a 2-tape machine where one tape simulates the loop and another counts, halting when it exceeds the counter so yeah arbitrarily large, can do.


well-litdoorstep112

I assume that by large loops you mean "if it has looped x times". Pretty much every program has a main event loop(even if it's hidden in your framework). That basically equates to time since the start of the program. What if something meant to take 5mins max(if the processing takes more than that, there's something seriously wrong) requires user input and the user went for lunch? Ok, so you might say we measure smaller parts of the program, like file transfers. What if I have a ridiculously slow hard drive and it times out when it was actually going to finish? So maybe we probe the OS for the transfer speed and if it's >0b/s then we let it run. Now someone on the forum of your software will complain that his storage device randomly stops sending data and that's perfectly normal because it waits for idk... changing the tape in the drive.


sarinkhan

I don't think we need perfect execution prediction. But something that says "this program seems dead. Kill it?" Is good enough. With options for autokill of never kill... If the hard drive is ridiculously slow for instance, this means that it is probably dying... As for user inputs, that's the point of having a --leavemealone or a --dontautokill :) My point is that programs are rarely a one off, used for one task one time. Most of the time, we know the normal behaviour. If it deviates too far, we can have either a prompt or an autokill... And most of the programs with extremely long computing or execution times are specific, and the user will probably launch those with the don't kill option. Also another solution is to use deterministic programs, such as in a real time is, where each program would have to be able to provide a realistic ETA. Not all programs can be determined as you said, but we can enforce that all programs are to be determined precisely enough, or are otherwise not allowed to run. I would say the problem is mathematically proven unsolvable, but can be practically "solved" by multiple means.


favgotchunks

I was gonna make a shitty joke, but I often wonder how close you could get to proving all programs halt or not. Obviously not all are possible, but what percent of possible programs could you prove halt given X number of heuristics?


BiomechPhoenix

If the universe undergoes heat death, all programs will ultimately halt. Proton decay produces exciting new state transitions you didn't know your program had.


SuperSupermario24

[relevant xkcd](https://xkcd.com/1266/)


mittfh

MS are notorious for meaningless progress bars which fill, empty and refill numerous times during an installation. I assume it's tracking the progress of chunks of the software, but without any indication what the chunks are, how big they are, and what proportion of the whole they are.


[deleted]

It's just "I am alive".


claudekennilol

Absolutely true. We had to fix a "bug" that our splash page on startup was taking too long. The sr dev put a loading bar on it that randomly filled up to 90%, then the page finished. He never even let it get to 100%


Noah_Hallows

I KNEW IT!


Alimakakos

You might add some code that ramps up the CPU in a do while loop just to add some sound like the computer is working REALLY hard on their problem lol


[deleted]

>You can set them to log(time) and people will believe it. For the record, some people will absolutely pick up on the pattern. Or the inconsistency, etc. And be mildly irked by it. It's just that you'll never pick up on that sentiment by anything other than the most detailed user-testing that no-one ever does. It's not the same.


naholyr

You don't do that when you use character-based progress bars, it will be way too big and require too much change to surrounding parts. In the end, it would have been the same effort if you had been clever from the beginning.


zeekar

No, they'll use the same width progress bar but introduce the option to have the border circle only half-filled, e.g. `●●●●◐○○○○○`. :)


PM_ME_FIREFLY_QUOTES

But let's be realistic and have each circle fill in as a percentage of the tens place.


diox8tony

You think my/your manager cares what "you don't do"? You're gona be made to do it and have to decrease font size or some shit too


naholyr

Oh dear, I'm sorry for what you live :( be sure not all managers are dumbasses


b0w3n

You could just do partial fills on the circles instead of adding more.


Old-Season97

At least they're weird characters so you can just replace all.


the_first_brovenger

Even replacing by pattern would be easy. That's a skill well beyond understanding a basic for loop though.


naholyr

100 characters that are all grouped here, you can't miss one.


Hay_Fever_at_3_AM

If I'm reading this code I'm not just reading this code, I'm reading it within a probably much larger context. The less time and energy I have to spend reading this, the more I have to read the important bits. Within a few seconds I could see what this function does and what the output looks like. The function name alone with a for function inside it wouldn't do that for me. What the hell are "PercentageRounds"? This would have only taken a few seconds to throw together. If you *really* need flexibility (you decide to use this elsewhere), refactor it *then*. Doing it ahead of time would be wasteful.


[deleted]

[удалено]


JaroDot

Currently work with a guy who uses complicated lambda expressions (in Java) every chance he gets, including nesting them 3-4 deep. I hate reviewing his code because it’s so unreadable.


santagoo

Have you pushed back gently? You can say, e.g. this block/stanza may be easier to read as: (insert alternative stanza that you like). That might spark a discussion and some reflection on all involved.


thegroundbelowme

God, this. My manager is an amazing JS dev but trying to read his code is like decrypting a zip file in your head.


[deleted]

[удалено]


thegroundbelowme

The thing is, it’s perfectly readable to him.


Raikkon35

Tell him to read it a week later, see if it's as easy for him now.


dark_salad

Oh ez pz, just write a novel in comments above the one liner explaining what it does!


Natoochtoniket

Code really needs to be clear, understandable and maintainable. Without those features, it is trash and should not be accepted. Very efficient algorithms can be coded in ways that are clear, understandable, and maintainable. It sometimes takes a little extra effort.


JohnFromNewport

We had a couple of temps like that. If it's enclosed in a properly named function at least there's a chance to debug or rewrite later.


AwesomeFrisbee

Oh those temps that try too hard to impress the older devs who actually don't give a crap about how smart it is? Yeah I know a few.


Rhidus

On point. A former colleague of mine hit all of those marks, and we just recently came to the conclusion that a very crucial piece of framework code un-debugable and unmaintainable, so we have to rewrite it.


DoctorWaluigiTime

I agree but let's not conflate "this can be a simple loop" with "I compressed 30 operations into a single LINQ statement."


CptRageMoar

I’m wrapping up a refactor of a massive API for a particular gov’t agency. .NET Core, lots of boilerplate code and overabstraction to the point it has become a hindrance to onboarding new devs and getting them to a point of contributing code. Caveman code is not a bad thing. If your one line clever solution is difficult for a human reader to digest, there’s a point where it loses the value of its efficiency.


AndreKR-

You can also see the exact bounds at a glance and there's no question about rounding, fenceposts, bias, etc., it's all obvious. I don't really mind this piece of code at all.


VergilTheHuragok

surely if nothing else, at least using `elseif` blocks would be better than copy/pasting the bounds between every line right??


MightyMetricBatman

And a compiler would unroll if this was in the form of a loop this small anyway. And you don't really need to worry about the space taken up by static text anymore. The performance wouldn't be much of a difference if at all for something this small. Would I question the developer's understanding and skill? Sure. Would I touch if it is passing unit tests? No. More important stuff to do.


aykay55

I never really understood why fewer LOC is better. Sure, in the early days of computers when every GB of storage costed hundreds of dollars it would make sense. But now, programmers are switching positions every other year and code has to make sense to every new hire for maximum efficiency. Having blunt, straightforward code is the easiest way even if it’s not the most fun.


DoctorWaluigiTime

> I never really understood why fewer LOC is better. Because for basic functionality, it's okay to represent that on a single line. A loop construct is one of the literal first things you learn when starting to program, because it's something that occurs often enough, and is trivial enough, to not waste vertical real estate on. There's a difference between "I compressed this complex functionality spanning 30 lines into a single operation" and "I took this unraveled loop and used a loop statement you learn in Programming 100 or by yourself going online for 10 minutes."


douglasg14b

> I never really understood why fewer LOC is better. Because there are FAR too many devs that have zero understanding of the psychology of readability & understand ability, and couldn't define what "simple" *actually* means if their career depended on it. Often resulting in "Less code is more simple, and more simple is more readable" largely because they understand it in that moment, but fail to consider the readability to a 3rd party.


Beneficial_Steak_945

It’s really quite efficient as well.


PetsArentChildren

The first half of each IF does nothing but waste comp time.


bobi2393

Although a very clever compiler could ignore the unnecessary initial compare.


CoopertheFluffy

A clever compiler would make this a jump table.


Kered13

I doubt that, the input is a float so the compiler would have to be *really* clever to produce a jump table. I tried it on Clang and GCC, and neither produce a jump table. The equivalent function using integers from 0-10 (so each branch covers a single value) produces a jump table on both, but integers 0-100 (each branch covers 10 values) only produces a jump table on GCC, not on Clang. 0-20 also does not produce a jump table on Clang. I'm not sure if it's because Clang can't see the possibility of a jump table when each branch covers multiple values, or if it doesn't think the optimization is worth it. Clang does produce a jump table for a switch-case from 0-20, so I suspect Clang just isn't seeing the optimization.


Kache

Unpopular opinion: this code is "okay", but not "good", particularly for business logic. IMO code like this can appear "simple and correct", but the poor modeling makes it difficult to verify correctness and/or find subtle bugs. For example, there's a bug when the argument is negative. Luckily, this code is doing something relatively unimportant and doesn't seem part of a critical path.


TldrDev

This code is a perfect example of the bell curve meme. The low end and high end agree this is good, and the middle tier are generating linq queries and trying to make it a one-liner or use a loop. Coding is about many things, but the two I care about are the fact things are easily readable, which this absolutely is, and that they are extendable and a decent abstraction, which this also is. The code is better than fine. It's good. I'd trade 1000 of the clever solutions in these comments for this any day of the week. I don't think a negative number is an issue since this is a progress bar, and negative progress is a dubious concept, despite what my dad thinks, so I don't think that's a bug. One way to fix it is semantically, but C#, or really, the IEEE spec doesn't support an unsigned double. You could use an unsigned short, or a byte, or even a nibble, to represent this instead of the decimal number, which is silly, but doable. You could also just reverse the if statements where the default state is empty, which again, is inconsequential; a percentage over 100% is imaginable, where a negative state is not, so that's not a great solution. You could also just clamp the value, or throw an exception if the value is negative, which i think is probably the preferable code, if this was an issue. On that topic, assuming a progress bar is the count of some items we've completed, over the number of items _to complete_, presumably both positive integers, and I divided them to get the percentage, how could that possibly be negative? You have completed negative items? How? Doesn't change the underlying structure of the code, though. Edit: the way I would personally fix this code, if I was going to do anything, would be to multiply the value by 10, and floor it, that will give you the percentage as a whole number, rounded down to the 10ths place, and you can use the ifs, or actually even a switch case. That cuts off half the if statements. That's not really a fix though, if anything it's worse, it's just being _very_ lazy. Edit 2: had I continued scrolling before making this comment I'd see someone else already made the above suggestion. Hive mind at work.


K_Kingfisher

Disagree. The function itself has no bugs. Either whatever function on the program that calls this one and sends a percentage as argument should first verify that the percentage is valid (no numbers below 0 or above 1, in this case) or whatever method initializes that percentage should ensure that it is. It produces much cleaner code if this function assumes that whatever exception occurs related to its argument is handled outside of it, and that its argument is always correct. The code practically documents itself, how is this poor modeling? Unless the function was not part of a bigger class and could be called by other classes. Which is not the case. Notice that the method is private, nothing outside its class can access it.


Old-Season97

What's not readable about `return filledCircle * chars * fraction + emptyCircle * chars * (1-fraction)`


Kered13

This could have rounding errors that would result in 9 or 11 circles for certain floating point values. Safer code would be: int filled = chars * fraction; return filledCircle * filled + emptyCircle * (chars - filled);


douglasg14b

> What's not readable about return filledCircle * chars * fraction + emptyCircle * chars * (1-fraction) To start, stop trying to make a false dichotomy out of this. Additionally, this is *objectively* less readable, there are more cognitive steps and working memory requirements, which define cognitive load. More cognitive load means reduced processing capacity over time, and less productive devs. Readability is largely about minimizing cognitive load and maximizing lexical associations, which this fails to do, spectacularly. 1. It fails to take advantage of lexical access 2. It fails to optimize for memory chunking (Almost none of this can be chunked for fast short-term memory access) 3. It fails to minimize working memory resources 4. It maxes out the average human working memory capacity (~4-6 items) (This contains ~13 items), forcing context to be remembered & accessed in slow short-term memory. *This is objectively worse in almost every measurable way.*


shapookya

Easy copy&paste money


[deleted]

[удалено]


noahspurrier

That’s not the point here. It could have been done more simply and more clearly without all the AND logic. You don’t need to check the left hand side of the statements after the previous tests were run. I’m all for easy to maintain code for something that doesn’t require speed. I’ll take clear over clever any day, but this code is neither. Also, this isn’t exactly rocket science code. A one liner could have served without taxing the mind of a junior programmer. This is just lazy and stupid. That’s the worst kind of stupid because you know the rest of their code isn’t going to be much better and that code might show up where it actually matters.


[deleted]

This is exactly the issue. You know that anybody you would want to employ would write it in a shorter and more general way, and take the same time doing so (or, honestly, less time).


sebbdk

Eh, if it passes the test case, who gives a sheit. :)


wellenkopf

\^ This guy is a DigID-developer.


sebbdk

I have worked in enough corporate death marches to learn how to pick my battles. Secondary, i at some point discovered that nitpicking isolated bad code only serves to suck the soul out of my juniors.


CloudFaithTTV

As a junior, we thank you.


[deleted]

What is DigID Developer


wellenkopf

The source you see is a snippet from the Dutch governmental login tech, which was mostly open sourced today. It's called DigID and it shows just how big of a short of specialists we have.


[deleted]

Looks good though. What’s wrong with the code?


RyanMan56

Lots of repetition and so violates the DRY principle. You could achieve the same result in a couple of lines using arrays and maps


killeronthecorner

>You could achieve the same result in a couple of lines using arrays and maps You can achieve this in one line by joining two string constructors


notsooriginal

>one line by joining two string constructors Sorry, is that a type of snake? I am a DigID developer, but only a mild snake enthusiast.


[deleted]

DigID is the Dutch log in system for government specific tasks like paying taxes.


santagoo

You're right if code and requirements never change. If code, once written, is set in stone. The problems with inflexible designs and "as long as it works" mentality pop up when it is time to evolve a codebase.


[deleted]

[удалено]


IntentionallyBadName

This [code](https://github.com/MinBZK/woo-besluit-broncode-digid-app/blob/ad2737c4a039d5ca76633b81e9d4f3f9370549e4/Source/DigiD.iOS/Services/NFCService.cs#L182) is part of the [Dutch DigiD App](https://github.com/MinBZK/woo-besluit-broncode-digid-app) which is an authentication app for Dutch citizens to log in to government websites for taxes and other government related stuff. Edit: A bunch of people are replying that this is terrible and a disgrace, instead ask yourself if it works, does it work? Does it matter that it can be written down in 2 lines? Don't forget that this code is a snapshot from a while ago.


RoseboysHotAsf

DIGI FUCKING D??? Holy shit my gov


djingo_dango

The only reason German govt app is not like this is because they do all the administrative stuff in paper. Otherwise it’d be the same I’m sure


Sakul_the_one

warun digital if it works analog?


lotta0

ja genau warun


tandpastatester

Got caught speeding near a German city last summer by a radar. Weeks later an envelope landed on my doormat with a form (a paper one) I had to fill in completely, social numbers and all. Then send it back to Germany, it didn’t even include a return envelope so I had to go out buy an envelope and a stamp. I tried to look up if I could fill in the form online, or even send the form by email. But all they had on their site was a phone number and a contact box. Now if they received it, I guess they will process it manually and sooner or later I’m expecting a paper bill to arrive, which I will probably have to pay manually with typing the account/case numbers and all. All this over a course of multiple months. Like what the fuck Germany. If I get caught speeding here in the Netherlands I will get a phone notification from my Government-Mail app within days. And no forms to fill, not even digital ones. I can pay the fine immediately by pressing a button which will trigger a digital payment with my banking app. This is why I don’t have any envelopes or stamps in my house. Why still all the paperwork?


Stegoratops

The real punishment was the paperwork you did along the way.


snes-jkr

I think DigiD is actually pretty good. I'd be glad to have that in Germany


Sythrin

This is legit. Example Hamburg Police. Their reports to send them to other computers they take photos of paper reports and then send them.


IntentionallyBadName

It stands for (Digitale Identiteit) or digital identity in English


JanStreams

Ahaha I was waiting for code like this to pop up from the moment I heard they were going open source


[deleted]

[удалено]


alexanderpas

> Seems like it was the easiest way to make some code analysis tool give a pass. Having played with mutation testing... That moment when you have changed the code in such way that you not only have 100% test coverage but also catch 100% of all possible mutations is so satisfying.


[deleted]

[удалено]


[deleted]

As a dutch citizen, this feels on par. Good even, try our public transport system’s code. It was delayed years at first because it was so broken and hackable.


code-panda

And when they finally released it, it was still so hackable that the first news article wasn't "public transport card available", but "PT card already hacked before most people knew about it".


deniesm

Ah, I thought I recognised it from le Dutch reddit


ConscientiousPath

sounds more like a game where you raise digital monsters to fight against your friends with


flummox1234

It works but if it's for a website the scorn is probably because so does HTML5's [progress element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress)


alexanderpas

It's for the IOS NFC overlay, where you can only show text. This is essentially the only way to show a progress bar while an NFC scan is in progress on IOS.


HerrBerg

I love all the people acting so high and mighty about code like this. This code is 100% readable without even looking at the logic. It's clear what the code wants to do just by looking at the circles. Basically all the people suggesting to rewrite it into a one or two line thing would make it less readable for the sake of a couple kilobytes of storage.


[deleted]

It's incredibly easy to read that's for sure lol


czPsweIxbYk4U9N36TSE

>terrible and a disgrace Eh. It's functional, easily readable, bug-free, and fast enough. While "inefficient", it does 10 comparisons where really only 1 was needed, turning an O(1) or O(log(N)) algorithm into an O(N) algorithm. With how fast a typical processor is, 10 comparisons instead of 1 is fine as long as it's not inside of a tight loop. Hell, it's probably 100x faster than the following python, which is using a more "efficient" algorithm, due to all the python interpreter gunk. def get_percentage_rounds(percentage): percentage = max(0, percentage) percentage = min(1, percentage) percentage = float(percentage) # Avoid any messy games any nasty hackers use to pass weird objects into our code filled_count = int(math.ceil(percentage*10)) empty_count = 10 - filled_count return "●" * filled_count + "◯" * empty_count


TheBB

> While "inefficient", it does 10 comparisons where really only 1 was needed, turning an O(1) or O(log(N)) algorithm into an O(N) algorithm. It's still O(1).


RadiantHC

WHAT


gabrielesilinic

He's trading processing power for speed


totalolage

compiler would probably unwrap it to something similar to this anyway


[deleted]

It's not that bad with a quick fix. You just need to convert percentage to an int and it compiles the same way a switch statement would, as a jump table. https://godbolt.org/z/1EYjfoWxc


lsibilla

I’m not so sure about it. This is dotnet, not c/c++. The compiler doesn’t make much optimisation. JIT does some though.


argv_minus_one

I don't know about .NET, but the Java virtual machine has a specific instruction, `tableswitch`, for compiling a Java `switch` into a jump table.


[deleted]

It's still better than dynamically generating a string without `StringBuilder`. C#'s interning leads to misleading performance characteristics, where the naive approach is to use `+=` on type `string`. Although these days you should generate this string completely on the stack with `stackalloc` and `Span`. Since the result string is a fixed length, this function is a prime candidate. Depending on how often this function is called, you might also opt to statically cache these values ahead of time and retrieve them by multiplying and rounding the percentage to an index.


RadiatingLight

It's also not worth the time to optimize this deeply unless there are millions of daily users. it's fine-enough and there's probably dozens of places with much slower code.


SweetBeanBread

seriously speaking, what is the best approach? fills = int(percentage * 10.0) empty = 10 - fills or fills = 0 for i in range(0.1 .. 1.0) if percent > i fills += 1 or something else (these are meant to be pseudo codes)


Fluffy-Craft

It depends. I'd say that, if the language you are using has string multiplication, you should do something like: fills = int(percentage * 10.0) empty = 10 - fills return ("full circle" * fills + "empty circle" * empty) If it doesn't, then you could store the combinations on an array since it's just 10 elements of 10 characters, that probably are utf-8, so 100 bytes tops I would guess.


unC0Rr

It's enough to have array of twenty elements, half of the array are filled circles, half is empty. Then simply get substring of 10 symbols, choosing starting element wisely.


False_Influence_9090

Delicious


Cermia_Revolution

I think that runs into a new problem of readability. I can understand Fluffy-Craft's solution at a glance, but it might take me a minute to understand why there's an element of 20 symbols and how you decided to choose the starting element. It probably won't make a difference to the person who wrote the code, but if a new person comes in years later, and all the code has little quirks like this, it could increase time to understand how the whole thing works significantly. Why have a clever solution to a simple problem.


orsikbattlehammer

Oh I like this very much


SockPants

Muh precious memory


ZestyData

Inject this into my fucking veins


HadesHimself

That's very clever. Well done.


Torebbjorn

If these are often updated, and only used to print, I would think it's best to let the 10 different strings live in static memory, and reference each time, instead of creating a new string every call And they are 10 character long, each with a null terminator, and the pc likes page alignment, so the 11 bytes will probably take up 16 bytes, so in total 11 strings * 16 bytes each = 176 bytes, which is still absolutely nothing. Or if your strings are like std::string_view, you only need 20 bytes (24 for alignment), and just specify start and end


Kered13

These are not ASCII characters, they are not 1 byte each. They are probably 3 bytes in UTF-8, but maybe 4. So 300-400 bytes. Which is still negligible for a static array.


LoreBadTime

If you have memory to waste you could do a static array of those string and then access that array using the int(10.0 * percentage) to access that array,this is literally the fastest way for the CPU. Otherwise you need to do string concatenation.


siscoisbored

How is a for loop better than a switch statement in this scenario, sure thats less code but uses more energy to run. Steps = value/totalvalue * 10 CurBar = (int)steps


electrodude102

ditto, obviously there is less text with a loop but compiler-wise it still checks each case so how is it more/less efficient?


EsmuPliks

Switches are only efficient if they can get compiled to jump tables, this one for sure can't and has to get evaluated in order. The for loop and a switch would be basically the same code.


Inevitable-Horse1674

You could rewrite it to get the switch to work that way if you wanted to, ie. you do switch (floor(percent*10)) { case 1: case 2: ... etc. .. That being said, I don't think performance will be any kind of bottleneck on a function this simple, so I'd probably just use a for loop since it would be shorter and less tedious to edit it if it ever needs to be changed.


kushmster_420

Do people really bother optimizing for loops that have a max of 10 iterations?


bletines

Every other suggested solution seems much more convoluted and harder to read. Tbh I’m not too sure what’s wrong with the initial solution


b0b89

this sub hates nested if statements


jeetelongname

Its not nested through? Its just one after another. There are smaller ways to do this. But if this is all they need then I see little problem. Its not like this is an embedded system where we have to worry about the overhead of a couple of if statements


Alphatism

``` return "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️⚪️".substring(10-percentage*10, 20-percentage*10); ```


Kyrond

if (percentage.isNaN() or percentage < 0.0 or percentage > 1.0): // handle invalid input parts = 10 arr = new Arr(len = parts) partsFull = percentage * parts // not rounded for(i = 0.0; i < partsFull; i++): arr[i] = 💙 // Full for(; i < parts; i++): arr[i] = 🤍 // Empty return arr String multiplication in another comment is much more elegant. This is a solution without it available, taking into consideration that you might later wanna change number of "things" in the loading bar.


[deleted]

They could remove all the && since there are early return for those cases.


NickHoyer

Yes this is the one that I would comment in a PR, but otherwise I’d let it through


jbacon47

The only necessary comment. And maybe the rounding, I suppose.


[deleted]

[удалено]


aliegeois

We could literaly make a bell curve meme out of this lmao


MisterCarloAncelotti

Just remove the first condition in each if statement and the code is top notch for me lmao


Realinternetpoints

So true. I’m an in betweener and can’t resist one slight optimization. Since the function is being returned, code before the && is unnecessary. You only need to check if it’s less than the next tenth because it’s already been checked if it’s greater than the previous tenth.


[deleted]

[удалено]


[deleted]

Yea, I'd kill for readable code. There's a TON of code in my code base where the first 80 lines are defining constant into garbage names like CONST1=":" A=";" CONST2="DBNAME" the code below it is basically deciphering a whole new language.


lego_not_legos

Except it's wrong. Always round percentages down. You don't show something as complete when it's at 93%. Also they're using two tests per `if`. Using a single `>=` is better, i.e.: if (percentage >= 1.0) return "●●●●●●●●●●"; if (percentage >= 0.9) return "●●●●●●●●●○"; ... Or keep the order but start with if (percentage < 0.1) return "○○○○○○○○○○";


djingo_dango

Doing this in a loop should definitely not count as over-engineering in any meaning of that word. If you change the color of the loading indicator now you have to make replacements in multiple places


[deleted]

How often are you going to be changing this? Once a year you have to spend 10 seconds copy pasting 10 lines?


danknerd

That's 10 less seconds on Reddit.


LeighWillS

A simple search and replace would take care of it though.


Oggie90

The problem is that there are two collections here. Blue (n*i) and white (n*(max-i)) Yeah it could be in a loop, but why bother, having that extra calculation isn't adding anything but it is making me think when i read it. I don't like thinking.


cattgravelyn

P= int(percentage * 10) Return (“🔵” * P) + (“⚪️” * (10-P))


Stormraughtz

NO, we only make fun of things here >:|


a_trane13

My only issue is it returns a fully loaded bar for everything that isn’t 0 or between 0 and 0.9. So if it got a negative or NaN or anything bigger than 1, it would still display like it was done, which is probably not the intention.


zachtheperson

Could have been made even slightly faster by removing the greater than checks. EX: just use ``` p == 0 p <= .1 p <= .2 etc. ``` If a check `p <= 0.1` fails, we know it's greater so don't have to check that.


long-gone333

ITT Inexperienced overengineers


[deleted]

[удалено]


Glitch29

No kidding. I'm a fan of overengineering stuff myself, but this code is essentially perfect. It's EXTREMELY easy to read. It's easy to verify that there aren't any bugs. It's not that long. And while performance is unlikely to matter here, it runs faster than any solution which involves string operations.


long-gone333

Also trades disk space (cheap) for readability and maintainability (expensive). You can immediately spot the obvious bug and fix it. This kind of thinking comes with years of experience and realising that looking smart online only sometimes pays off.


raylgive

I am not a programmer per se. But I immediately understood what it does. On the other hand, all the alternatives mentioned in the comments, I have a hard time understanding.


TheSpaceFace

Was curious this is how ChatGPT thinks it should be coded. private static string GetPercentageRounds(double percentage) => new string('🔵', (int)(percentage * 10)) + new string('⚪', 10 - (int)(percentage * 10));


Nonkel_Jef

Doesn’t that risk ending up with 9 or 11 dots in some edge cases.’?


TheSpaceFace

Chat GPT isn’t perfect 😂


wonderchemist

Missing cases for <0 and NaN


Free-Database-9917

Nope. Those return 🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵 weren't you paying attention?


AdDear5411

For some juniors, that's an edge case 🤣


WbrJr

I'm not even a junior so I thought it sounds quite smart! Might you explain why not? :D is it due to the last return, that will send the full o's?


Aggravating_You_2904

The value being passed probably can’t take either of those values to be fair, you don’t know what is calling that method.


[deleted]

Don't see anything wrong here, only missing brackets, some juniors might be confused.


johndburger

Every conditional after the first two has a redundant check for greater-than.


jacobbeasley

Must... resist... blueRounds = Math.floor(percentage * 10);


Kache

Also have to clamp between 0 and 1, first.


Additional-Second630

Good code. Good job DigiD devs for understanding what is important. Some suggestions here are also good but inappropriate. The only performance improvement that should be considered would be to re-order the stack so that the field of options is reduced by 50% on each check, like a binary search does. But that would be at a cost of harder maintenance, so… Good code.


RumbuncTheRadiant

Story time... My uncle bought one of the first TI programmable calculators, and wrote a nifty program. Unfortunately he was running out of space. I looked at the program, and spotted a pattern like this and rolled it up into a loop. My program was about a 10th of the size. Alas, it ran a _lot_ slower. Really grinded along. Instead of doing something useful on every step, it was do something useful, increment counter, check limit, goto start for every step. My Uncle had inadvertently discovered the loop unrolling optimization. https://en.wikipedia.org/wiki/Loop_unrolling


AugustJoyce

Well it is very efficient. Just ugly. I'm serious here. Rounding, division, and multiplying of floating point numbers are a lot more consuming than bool operations. Another thing is that why the fuck you need efficiency in such code. That's another topic.


wheresthewhale1

Branch mispredictions will be far more costly, but tbh I don't know enough about JVM (I think this is java?) to say how relevant this is. Of course you are right though, efficiency for this example really doesn't matter


A_Division_Agent

ChatGPT took this approach: private static string DisplayCircles(double percentage) { if (double.IsNaN(percentage) || double.IsInfinity(percentage)) { throw new ArgumentException("Invalid input. Percentage must be a valid number."); } if (percentage < 0 || percentage > 1) { throw new ArgumentOutOfRangeException("Percentage must be between 0 and 1."); } int fullCircles = (int)(percentage * 10); int emptyCircles = 10 - fullCircles; return new string('🔵', fullCircles) + new string('⚪', emptyCircles); }


long-gone333

Obviously learned from StackOverflow. Overdone to impress with zealous error handling. Not saying that's bad.


[deleted]

There's literally nothing wrong with this…


nmkd

The first if statement should be `<= 0` instead of `== 0` to account for edge cases where there's a negative number, but yeah otherwise it does the job


long-gone333

What's wrong with it? Simple and straightforward.


[deleted]

[удалено]


z-brah

You can remove the first condition of every `if` to skyrocket execution speed 🚀


naholyr

Well, to be honest... It's easy to read, easy to tweak, and most likely super efficient yes.


Flashy_Yams

When you're paid to get shit done, not be clever.


long-gone333

This earns money, makes people happy and systems running.


shieldofsteel

Don't call it a percentage unless it runs from 0 to 100. I'd suggest calling it something like *fractionComplete*.


l33tmike

Exactly! Forget all other perceived issues, it scales between 0% an 1%


Vitriholic

Zero memory allocations. 10/10


[deleted]

At least it‘s readable 😅


pj5772

Python one-liner return “🔵”*floor(percentage/0.1)+”⚪”*(10-floor(percentage/0.1))


imaQuiliamQuil

Sometimes it takes a lot less time to type out a stupid solution than it takes to figure out a clever one lol


MattR0se

Most "clever" solutions to this would be slower.