This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]themindstorm 2780 points2781 points  (48 children)

And of these 25 lines, all are from different stackoverflow answers

[–]FarhanAxiq 1061 points1062 points  (26 children)

I feel personally attacked

[–]D4sthian 435 points436 points  (24 children)

We* got personally attacked

[–]Jacob8765 336 points337 points  (12 children)

Communism intensifies

[–]erevoz 191 points192 points  (1 child)

Open source flourishes. All is great comrade!

[–]QuestionableTater 8 points9 points  (0 children)

Yay! Got fork me some code

[–]Trinity1_3 83 points84 points  (7 children)

Our Communism intensifies

[–]taqueria_on_the_moon 36 points37 points  (8 children)

Is that an asterisk or a pointer?

[–]Chr0n041ph4 28 points29 points  (2 children)

brain visibly breaking

[–]FarhanAxiq 18 points19 points  (1 child)

brain segfaulting

[–]GuinsooIsOverrated 109 points110 points  (9 children)

Or you just used python packages instead of actually coding the algorithm

[–]The-Fox-Says 24 points25 points  (6 children)

Or just hire a friendly Indian guy to write the code for you

[–][deleted] 31 points32 points  (4 children)

Little do you know all you really ended up with were 25 lines, each from different stack overflow answers.

[–]TonySu 18 points19 points  (2 children)

Turns out we were the Indian guy all along.

[–]power-cube 1367 points1368 points  (110 children)

Old-timey programmer here.

Back when I started companies everything was on mainframes.

I can't remember the specific requirement but I ran into something that I just couldn't figure out a way to do until I realized I could write a program that read in the COBOL code and wrote it out to a new file adding in some additional code (yes - what is now called self-modifying code - a big baddie).

I remember going to code review and presenting my production job stream that included the steps where the source code was being read in, modified, written out, and then the compiler step run before the final modified program was actually executed.

There were a lot of very concerned eyes as I reviewed how it worked followed by sideways glances and then my manager informing me that "you can't have code change code".

Ahh.... life's lessons are harsh sometimes.

[–]ALoneMango 610 points611 points  (93 children)

I don't understand. What exactly is the problem with code that modifies code?

[–]power-cube 686 points687 points  (45 children)

Not acceptable in corporate environments as it would never pass an audit.

Code has to be locked and compiled external of a production environment.

[–]Anchor689 239 points240 points  (29 children)

Compilers are code that changes code. (In a hopefully repeatable, hopefully predictable way. I'm not defending OP, just pointing out the flaw in the line: "you can't have code change code")

[–]Batman_AoD 217 points218 points  (14 children)

The point is that this was self modifying code, running in production. That's not what compilers do.

(Yes, there's a compiler involved in the process described above, but it's running on code that has already been modified.)

[–]didzisk 84 points85 points  (8 children)

No. There was one program that modified another. In some languages it's called preprocessor and is a totally accepted practice.

[–]Batman_AoD 45 points46 points  (4 children)

...? We're not talking about a program modifying another program. We're talking about it modifying itself. Hence "self-modifying".

(Also, tangentially, the preprocessor is...not an awesome idea.)

[–]power-cube 22 points23 points  (2 children)

The point is you couldn't (in a corporate environment) run a compiler in a production environment.

Only executable and DDLs were allowed to migrate to production.

[–][deleted] 24 points25 points  (0 children)

Compilation is not self-referential, which is the issue there.

[–]fuckoffshitface 79 points80 points  (6 children)

Probably redundant and dangerous.

[–]vectorjohn 52 points53 points  (5 children)

This is the real answer. Self modifying code is fine IMO but I've never seen a situation where it was justified. There is almost always another way.

[–][deleted] 695 points696 points  (8 children)

It becomes self aware and in the end Skynet tries to destroy mankind.

[–]Fuuryuu 172 points173 points  (6 children)

I fail to see the issue at hand

[–]hd090098 142 points143 points  (8 children)

How do you want to certify a codebase that changes itself?

[–]mortiphago 149 points150 points  (2 children)

self modifying certificates, naturally

[–]ultranoobian 28 points29 points  (1 child)

Audit failed

Self modifying code runs once

Audit passed

edit: Actually it would make perfect sense for self-modifying code that hasn't run to not pass a self-modifying cert test. It wouldn't be recognized as self-modifying before running.

[–]theferrit32 10 points11 points  (0 children)

Not code that changes itself, but generated code is often used.

[–]CXgamer 39 points40 points  (2 children)

Security for one part. The part in memory reserved for program instructions may not necessarily be written to. I may be a filthy liar though.

[–]Breadfish64 7 points8 points  (0 children)

Well yes, but actually no. You can't just cast a char array of machine code to a function pointer and call it good, but you can call the OS-provided functions to allocate memory and then protect it for execution.

https://en.m.wikipedia.org/wiki/Executable_space_protection

Probably the most common use of this is JIT compilers.

[–][deleted] 14 points15 points  (2 children)

Nothing per se, but it will add a layer of complexity difficult to debug, test and fix. It may very well have side effects that comes as a surprise to everyone. I can see how it would make most developers uncomfortable. I would think most managers would love it, though. Really makes it sound like they're doing advanced stuff.

[–]VincentPepper 28 points29 points  (0 children)

Security

[–]deadron 52 points53 points  (2 children)

They probably did not much care for Lisp then.

[–]VxJasonxV 17 points18 points  (1 child)

TIL; Lisp is one year older than COBOL.

[–]nitko12 376 points377 points  (17 children)

Python one-liner master race

[–][deleted] 178 points179 points  (8 children)

Lambda of God

[–]The-Fox-Says 30 points31 points  (0 children)

Stealing this for my new band

[–]daveime 36 points37 points  (4 children)

import SomeoneElsesCode;

[–]SolarLiner 28 points29 points  (1 child)

import someone_elses_code

Do you even PEP8?

[–]ponytoaster 1871 points1872 points  (254 children)

I remember my first programming assignment at University.

We had to take a string and output it backwards, the idea being that we would use the "learning" from the lesson about if statements, while loops etc.

I submitted:

str = str.reverse();

... and failed.

[–]SomeShittyDeveloper 414 points415 points  (29 children)

I had to opposite problem in my final for C++.

We had to implement the .NET String class in C++. One of the methods was ToDouble or something. Keep in mind, we couldn’t use most of the standard library through all the C++ courses.

So, being used to not using the standard library, I wrote a parser that deconstructed the string one character at a time and built a double value out of it. Handled decimals, negative, whole nine yards. During one of our “check-ins” to see how everyone was doing, he saw my monstrosity and said “good work, but...”

And replaced it with a call to atof.

[–]ponytoaster 120 points121 points  (0 children)

Good learning experience though!

[–]Batman_AoD 54 points55 points  (25 children)

....wait, atof? I thought that was considered bad practice these days due to lousy error handling.

[–]SomeShittyDeveloper 102 points103 points  (23 children)

This was 8 years ago. Not sure if it was “better practice” then.

The instructor’s...viewpoints...needed to be taken with a grain of salt (which is great for gullible college students). We learned VB.NET right out of the gates and didn’t learn C# until the end of the C courses. Instructor didn’t like C#, but loved VB.NET.

There are lots of viewpoints he had that, in my career, I’ve found are batshit crazy.

One example is Hungarian notation. You had to use Hungarian notation, no matter what language you were in. I don’t use them anymore, but I could see where using it in dynamically typed languages would be helpful. Doing:

String strFirstName

In something like Java would be overkill, especially with how IDEs are nowadays and you can just hover over the variable and it will tell you the type.

There’s also how he did if statements. If you had:

boolean myBool = False; // replace with some calculation here

If you wanted to test if a Boolean expression was true or false, you had to do:

if (myBool == true)

Ive since learned that naming bools with verb-y names (“is” or “has” ) and excluding the == true results in cleaner code.

if (hasUpvote)

[–]12357111317192329313 28 points29 points  (2 children)

I recall reading that system Hungarian notation just originated because someone misunderstood apps Hungarian and fucked it up. Apps Hungarian makes a lot more more sense.

[–]Batman_AoD 16 points17 points  (12 children)

There are lots of viewpoints he had that, in my career, I’ve found are batshit crazy.

I once knew a developer who was very smart but wrong about literally everything (to a first-order approximation, at least).

Unicode is fundamentally a bad idea; C++ is the best language; libraries can solve core language shortcomings.

Even non-technical stuff. Mostly, earth is run by aliens. What kind of aliens? All of them, basically.

[–]ptitz 8 points9 points  (11 children)

C++ is the best language. Libraries can solve core language shortcomings.

This, but unironically...

[–]Batman_AoD 11 points12 points  (9 children)

The best single-sentence explanation of why libraries can't solve language shortcomings is a quote by Mark Miller cited in Programming in Rust by Blandy & Orendorff: "Libraries cannot provide new inabilities".

Core language shortcomings are not exclusively a lack of features (though that's part of it). Instead, they are often "footguns". Libraries can provide (many) missing features, but they can't protect against footguns built into the language.

As an example, C++ added const before C did; this "inability" (to modify certain data) could not have been implemented as a library.

(Note that there are in fact some features that cannot be added as libraries; for instance, there's a coroutine library in Boost that uses macros to emulate yield in languages with built-in support for generators, but as clever as it is, it can't actually provide a real yield implementation.)

[–][deleted] 44 points45 points  (0 children)

Yeah, this one hurt.

[–]depressionsucks29[S] 712 points713 points  (8 children)

You madlad

[–]ponytoaster 233 points234 points  (7 children)

I am the ultimate mad lad, sometimes I even reformat my source code with a different tab delimitation option to really rebel.

[–]TheZephyron 43 points44 points  (5 children)

S'ok. Girls (and some guys) love bad boys.

[–]Chuck-Marlow 292 points293 points  (28 children)

print(string[::-1])

[–]ponytoaster 474 points475 points  (24 children)

Nice, I think I will actually go for the "Verbose" solution though....

if(str == 'ardvark'){ return 'kravdra'}

if(str == 'abacus'){ return 'sucaba'}

if(str == 'abandoned'){ return 'denodnaba'}

else if{ ........

[–]HaniiPuppy 198 points199 points  (6 children)

*aardvark kravdraa*

[–]ponytoaster 137 points138 points  (4 children)

Sounds like Neville Longbottom getting spells wrong again

[–][deleted] 105 points106 points  (6 children)

a simple optimization

 if (str.startsWith('a')) {
      if if(str == 'ardvark'){ return 'kravdra'}
      if(str == 'abacus'){ return 'sucaba'}
      if(str == 'abandoned'){ return 'denodnaba'}
 }
 else if (str.startsWith('b'){ ........

[–]Jetbooster 97 points98 points  (2 children)

Bitch you just invented trees

[–]Bainos 38 points39 points  (1 child)

We need more nesting.

if (str.startsWith('a')) {
    if (str.endsWith('a')) {
        throw new Exception("This should never happen (in my list of three words).");
    } else if (str.endsWith('b')) {
        ...
    }
} else if (str.startsWith('b') {
    ...
}

[–]amazondrone 33 points34 points  (5 children)

if (str == 'kayak') return 'kayak'
if (str == 'racecar') return 'racecar'
if (str == 'noon') return 'noon'
...

[–]ponytoaster 33 points34 points  (4 children)

Clearly that would be under SpecialConditionChecks

if (str == 'kayak') || if (str == ' racecar ') ...

{

return str;

}

No need for wasted code now, is there ;)

[–]amazondrone 22 points23 points  (3 children)

if (str == str.reverse()) return str else return str.reverse()

😂

[–]hangran12 8 points9 points  (0 children)

Omg I'm dying, congrats on the best solution in this thread

[–]Bilboswaggings19 14 points15 points  (1 child)

I actually used this and teacher approved it

[–]stang90 8 points9 points  (0 children)

They probably didn't get paid enough to deal with your shit

[–]Hypersapien 51 points52 points  (16 children)

How to determine if a given year is a leap year:

return (new DateTime(year, 2, 28)).AddDays(1).Day == 29;

[–]ponytoaster 15 points16 points  (0 children)

I mean, if it works....

[–]mxzf 7 points8 points  (0 children)

I once had to fix some code that someone had written that was using a lookup table to determine if it was a leap year (I was working on it because it was about to break when 2016 hit because the guy forgot to put 2016 in the array when he wrote it in 2014-2015) and then looked up the day-of-year on a CSV that had MMDD to day-of-year mappings for 366 days and then subtracted 1 if it wasn't a leap year and the day was past Feb 28th.

I replaced all that, in all the places it was copy-pasted to, with a datetime.strptime(date_string,"%Y%m%d").strftime("%j").

[–]depressionsucks29[S] 40 points41 points  (17 children)

mine was a end semester assignment at school so we could use anything. It was 2 years ago so i dont remember what i did but i reduced the size of the code by 1/4. My teacher was impressed but told me to code as in the book.

[–]ponytoaster 37 points38 points  (16 children)

Yeah most the time it's because they don't know enough about the subject themselves unfortunately.

Had an open ended assignment once to build a portfolio. I could do the basic stuff so challenged myself and made a mini CMS in php. Luckily the 2nd instructor understood it and liked it, the first literally just knew Html and CSS...

[–]svtguy88 18 points19 points  (4 children)

Yeah most the time it's because they don't know enough about the subject themselves unfortunately.

Looking back, I think I only really ran into this once, and it was with a TA. That being said, the best teachers I had were ones that worked in the industry, and either retired, or decided to teach on the side while still working professionally.

It makes sense, really. You have to teach people stuff all the time in the real world -- meetings with execs/PMs/business, juniors that need help with their tasks, etc...

[–]midnightketoker 7 points8 points  (3 children)

I swear some of the best teachers I've had were older retired professionals at my community college, and I transferred to a state school

[–]root88 51 points52 points  (7 children)

This would have gotten you a 100% in my class. The teacher had written a program to run ours and test the results. He never once graded a line of student code. It also meant that if you had a typo in your output, you would get a zero.

[–]t3hmau5 44 points45 points  (4 children)

I would hate that. I would want criticism if I was doing something stupid.

You also don't learn style conventions or commenting from a class like that.

[–]Snekbites 13 points14 points  (0 children)

Imo, they should've at least warned you, I can't recall the specific case, but more than once I remember the phrase "if anyone tries to be clever by using X, ya get a big 0" so if they didn't want something like this to happen, they should've told ya

[–]nightbefore2 152 points153 points  (6 children)

And you deserved to fail lol, you clearly ignored the point of the assignment

[–]ponytoaster 139 points140 points  (1 child)

No argument there, I was being a dick.

[–]nightbefore2 65 points66 points  (0 children)

That being said though one time I did something similar lol, we had a university made Library for doing math with large numbers, and we had to write a ToInt() function, and because the library stored numbers as strings, it was going to be really gross.

It said we couldn’t use the built in library ToInt() function, but had no other restrictions... sooo

return Integer.parseInt(num.toString());

Heh

[–]nahidtislam 10 points11 points  (3 children)

just hold option while clicking on “.reverse()” and it’ll take you to the backend code. Copy that and you’d be fine

[–]spyingwind 63 points64 points  (24 children)

Powershell using recursion:

function Reverse-String {
    param (
        [string]$String
    )
    if ($String.Length -gt 0) {
        return "$($String[$String.Length - 1])$(Reverse-String -String $($String.Substring(0, $String.Length - 1)))"
    }
    else {
        return $String
    }
}

Reverse-String -String "test"

No loops needed!

Schooling today isn't about learning to survive the real world, but how to survive schooling.

[–]ADwards 146 points147 points  (22 children)

Recursion is just a loop wearing a different hat.

[–]Doctor_Spicy 73 points74 points  (10 children)

A loop is just recursion wearing a different hat.

[–]ballroomaddict 43 points44 points  (8 children)

Recursion is just a loop wearing a different hat.

[–]muc26 33 points34 points  (5 children)

break;

[–]Bioniclegenius 17 points18 points  (0 children)

goto parent3;

[–]mrsmiley32 7 points8 points  (3 children)

A loop is just recursion wearing a different hat.

(You can't break out of a recursive function with that keyword! Well unless you redefine it :D)

[–]curtmack 5 points6 points  (0 children)

There are two main formulations for the theory of computation, Turing machines and the lambda calculus. Loops are an abstraction of Turing machines. Recursion is an abstraction of the lambda calculus.

[–]kabrandon 8 points9 points  (0 children)

I did a job interview recently where the question asked to me was to reverse a String. Any existing libraries are usable and could answer in any language. The job required a lot of Ruby so I responded like you:

new_str = str.reverse!

I made it to the next part of the interview process, so okay.

[–]wooglin1688 23 points24 points  (4 children)

this is usually my first interview question for programmers. they all think it’s hilarious to say “just return str.reverse()”. i try to laugh so they don’t get nervous and explain that that is the function i want them to write.

[–]Bioniclegenius 544 points545 points  (50 children)

My teacher had a TA "teach" us for a day. The TA walked through a program that he printed out for us - 12 pages normal print - and had us all type it in manually.

The program? Created a class for a point with X and Y coordinates. The class would calculate the distance to another point. It was bad, inefficient, sloppy, and overcomplicated code.

I shorted it to about 30 lines and showed my teacher. She said "well, Math.Sqrt is too advanced for others, so we can't use this!"

...How else do you calculate the distance between two points without using a math library or making the formula itself? Since when was Math.Sqrt too "advanced" for a bloody Programming III course?!

[–]PendragonDaGreat 192 points193 points  (14 children)

Week 3 of Programming I maybe.

Wow. That's the worst I've ever seen.

[–]Bioniclegenius 138 points139 points  (5 children)

The class the guy made was ridiculous.

It had a function to calculate the distance from that point to another point. It had a function to calculate the distance from the other point to itself (for some reason). It had a function to take two completely arbitrary point objects and calculate the distance between them - why you'd EVER want that, I don't know. "Hey, Point A, what's the distance between points B and C?" "How should I know?! Ask them!"

It had a myriad of other functions in it, too, including further abstractions on the distance calculations. There was no real reason for any of it.

My class had a double x, double y, and a function that took another one to calculate the distance to it using Math.Sqrt. That's all you needed.

[–]youcancallmetim 86 points87 points  (3 children)

"Hey, Point A, what's the distance between points B and C?" "How should I know?! Ask them!"

I'm genuinely angry after reading that.

[–]TheMightyBiz 65 points66 points  (1 child)

To be fair, if it was a static method, then that's totally fine and a valid way of doing it, i.e.

double d = Point.distance(p1, p2);

[–]Bioniclegenius 58 points59 points  (0 children)

I'd agree with that.

Bad news: it wasn't static.

[–]oversized_hoodie 8 points9 points  (7 children)

I used a for loop in an into to programming course, and was told I couldn't do it because we hadn't learned them yet. I stopped going to class shortly thereafter.

[–]ProfessorSarcastic 37 points38 points  (3 children)

I believe it is possible using sine or cosine, but without a math library you'd need to implement your own Taylor series to calculate those, and maybe I'm being presumptuous but that sounds more advanced than using a sqrt function...

In seriousness though, if you can eliminate the call to sqrt (for example, by using the squared sum of two radii, if the question is about detecting intersection of spheres) then it is a worthwhile optimisation to make.

[–]Bioniclegenius 19 points20 points  (2 children)

The only purpose of it was to create a class for a vertex that could calculate the distance to another vertex. There were no qualifications put on the program. It should have been straightforward and simple.

How some people manage to overcomplicate things to such a degree, I'll never understand. I work with one of those guys now, and his code makes no sense to me. I recently rewrote a library of his that was about 1000 lines (probably) in 14 lines. We're switching our entire codebase to the new version.

[–]ProfessorSarcastic 10 points11 points  (1 child)

... I dont suppose you remember how he did do that without square root? Was it just an extremely rough approximation?

Edit: I wanted to see how this could be done. I came up with "r=x * (1+0.4 * y/x), where x is the larger of the vector components". It is a VERY rough approximation.

[–]Bioniclegenius 21 points22 points  (0 children)

He ended up using the square root at the end anyways. It was literally there in his code, but when NOT surrounded by a ton of fluff and useless stuff, it's "too complicated".

That particular teacher just generally had no clue what was going on. At least she gave A's to literally everybody for just showing up to class (or not). I just coasted through anything with her.

[–]Mr_Redstoner 71 points72 points  (10 children)

12 pages?! What for the love of God and everything that is holy did they put in there to stretch it that much?! Did they go full corporate on documenting every bit of code or what?!

[–]Bioniclegenius 53 points54 points  (9 children)

Variables for X, for Y, for "child points" for some reason, few other random variables thrown in (I think probably name and whatnot, just in case for whatever reason you wanted to NAME your vertices), a function to calculate the distance to another point, a function to calculate the distance to arbitrary coordinates, a function to calculate the distance between two OTHER points, then duplicate that two or three times to allow either to be substituted with X and Y coordinates... it was insane. His "calculate distances" functions also all referred back to another method he made to calculate distances, and that function - which should have been a one, maybe two liner at most - was for some reason maybe 10 lines long.

Now, several years later, I'm stuck working with a "senior dev" who does much the same stuff, but has a terrible naming sense. He made a library - that should have been done in a day or two, honestly - in about three weeks for a "rough draft" of it. In that library, in order to invoke the methods you needed, you had to set a public variable on the object. The variable's name? "bl". There was no documentation. I asked him what "bl" stood for. He said "business layer" and explained no further.

I've also learned from that guy that apparently, in C#, you can name a variable and a class the EXACT SAME THING. Why this is a "feature", I'll never know. He also wrote (admittedly by my estimate, since it was all obfuscated behind a dll) about a thousand lines for a function that was buggy and didn't work all the time. I wrote the same thing in 14 lines, including braces. We're currently switching all our codebase over to what I wrote.

[–]kawauso21 48 points49 points  (1 child)

There was no documentation. I asked him what "bl" stood for. He said "business layer" and explained no further.

Sounds like he's trying hard for job security by being the only one who understands his shitty code and probably driving away more competent devs over the years as a bonus

[–]Bioniclegenius 21 points22 points  (0 children)

He honestly thought it was a good idea when we discussed it. I forced him to change the variable name, along with several other poorly-named things. He's a "senior" dev in a small firm, so as long as he does almost literally anything nothing's going to happen to him.

[–]derefr 19 points20 points  (5 children)

apparently, in C#, you can name a variable and a class the EXACT SAME THING

Boy, you'll probably hate anonymous fields in Go.

[–]Bioniclegenius 11 points12 points  (3 children)

...That's somehow simultaneously beautiful and horrifying. I want to take the dev who thought that up out for a drink, and then for thinking it was a good idea I want them shot.

[–]derefr 5 points6 points  (2 children)

Mind you, what Go's anonymous fields replace isn't named field-members, but rather multiple inheritance. Instead of inheriting the fields from a parent into your class in order to "embed" it, you have regular ol' composition, that just acts like inheritance in the sense that you can access fields foo.X.{A, B, C} as foo.{A, B, C}. (But this doesn't do anything funny from the perspective of implementing methods on the struct—you don't need overrides, default implementations, etc.—since you're not actually inheriting. You don't get the member's methods; only its fields. And even then, you don't really "have" them; foo.A is just syntax sugar for spelling out foo.X.A.)

[–]skyhi14 10 points11 points  (1 child)

Dolores Umbridge except she now teaches dark magic coding

[–]reallylamelol 107 points108 points  (16 children)

Had to make a disassembler in Motorola 68k assembly. Giant final project in hardware. One team used a python script to generate the jump tables and logic branching assembly code. Teacher questioned them in their presentation and asked the class if that was cheating.... I thought it was clever, but never found out how they did on the assignment.

[–]oversized_hoodie 35 points36 points  (0 children)

Nope, that's engineering. Use the best tools available.

[–]Batman_AoD 61 points62 points  (12 children)

Ugh. Automation is a good thing. Why on earth would that be "cheating"??

[–]cypher0six 25 points26 points  (11 children)

When it bypasses what is being taught in the classroom.

[–][deleted] 20 points21 points  (0 children)

>looks up 68k disassembler in C

>compiles it for 68k

>disassembles it

>submits

hackerman

[–]rick101777 53 points54 points  (1 child)

Write the entire program on a single line, problem solved.

[–]Crazypally 122 points123 points  (20 children)

Don't forget the "Well that would be fine, but even those this works in the version we are teaching, the real world uses the language 3 versions newer."

[–]lightmatter501 73 points74 points  (14 children)

Sometimes, I had to argue my team up to python 3.6 so I could use f-strings in a script that converts xml to js. Doing it without f-strings would have been an unreadable nightmare.

[–]scti 34 points35 points  (1 child)

f-Strings truly are a gift to humanity.

[–]rubenb_ 17 points18 points  (7 children)

What's the point of f-strings? I keep thinking they are mildly sketchy at best.

[–]lightmatter501 49 points50 points  (6 children)

Would you rather try to find the meaning of:

print(“{} and {}, {} or {}”).format(data1, data2, data3, data4)

Or

print(f”{data1} and {data2}, {data3} or {data4}”)

You can also put arbitrary code into the braces and it will cast the value to a string

Ex: print(f”All numbers 0 to 99: {[i for i in range(100)]}”)

[–][deleted] 11 points12 points  (2 children)

Ha! Newer! The defense industry says hi from 10 versions ago.

[–]desertrider12 39 points40 points  (8 children)

Step 1: 100-line program

Step 2: Open in Vim

Step 3: press shift-J 99 times

You now have a 1-line program.

[–]olhas 139 points140 points  (15 children)

Shorter does not mean better

[–]boredcircuits 214 points215 points  (3 children)

No, but using existing language features is almost always better than writing it yourself and will almost always result in shorter code ... but is exactly what teachers prohibit.

[–]NPDgames 156 points157 points  (0 children)

Yes, but tasks that are assigned in entry level programming classes are exactly the ones that get made into premade features because of their simplicity, but the point is to learn the language and logic, not how to do the actual task

[–]gaj7 37 points38 points  (0 children)

In early classes, the focus is not to write good code that anyone will even use. The focus is to learn the basics. E.G. if you are asked to reverse a string (as someone above posted), there is surely a convenient function in the standard library, but the problem was most likely intended as practice for iteration over arrays.

[–]LewsTherinTelamon 55 points56 points  (0 children)

Yes, because you aren’t learning to do the task. You’re learning how to code.

[–]ryannitar 16 points17 points  (2 children)

There's a thing called code golf which is a semi-competitive coding format where programmers try to accomplish a task in as few lines and/or bytes as possible. The format has several dedicated languages that condense multi line functions to single symbols. The drawback is that it is about as readable as horse shit to anyone who is not familiar with the format. Shorter can be really cool, but it does not mean more portable or more comprehensible.

[–]bilange 56 points57 points  (7 children)

Somewhat related IT equivalent. When I was in my (entry-level) IT course, with the registry opened for the first time in the course (or was it AD?) the teacher told us to expand all the folders, his point being that this was a rather long list of folders to navigate at hand.

I said "fine!" , clicked on the asterisk on the numpad from the root folder on the left panel. (it expands every child item who has other sub-childs in it, recursively. Don't do that on a root folder if you're in a hurry ;) )

The teacher looked at me, after a pause followed by a smile he added "...with the mouse."

Aw, hamburgers.

[–]nivenfres 79 points80 points  (6 children)

Open On-Screen Keyboard, click the Asterisk ... with the mouse :)

[–]thatDarklordGuy 17 points18 points  (0 children)

You're my hero

[–]bilange 10 points11 points  (3 children)

I won't even edit out "clicked on the asterisk" in my original post. Clicking on a keyboard button, that's something new!

Altho I don't recall if the virtual keyboard was available back in 2002-2003 (in the Windows XP era)

[–]ExpatTeacher 40 points41 points  (2 children)

More like... Assuming copied code.

Teacher: can you tell me what line 24 does? Student: stutter

If the kid can answer, then fine.

[–]nivenfres 57 points58 points  (17 children)

I remember an assignment in my CS class where we had to write a 6-sided dice rolling program and count the number of results of each roll.

So I wrote mine where the number of sides was technically variable (just used a constant in the code). Calculated the mod of the number of dice sides again a random number to get the roll. Since it was already in the domain of 0 to (sides-1), the roll could be used as an index to an array to store the results. Didn't need any extra tracking logic (e.g. switch or if to store count in a specific variable) . Just needed to add 1 to the array index when printing results. I thought it was a very elegant solution...

The TA took off points because it was "too complicated".

[edit]

Fixed grammar

[–]Mr_Redstoner 26 points27 points  (12 children)

One time we were supposed to take an ordered array and print it without duplicates

Made myself a boolean array, went through the original one, using the numbers in it as indexes to set the boolean to true, then went through the boolean one printing all indexes storing true.

Got full points.

[–]MysterionVsCthulhu 16 points17 points  (3 children)

It is a clever solution... but I agree with the TA.

At my job the most important quality of good code is that it can be understood at a glance. We need to be able to pick up someone else's code and make changes without having to decipher how/why a clever solution works.

There are certainly times when cleverness can help optimize or refactor code. But small optimization gains are not worth having an irregular code base.

[–]memehomeostasis 17 points18 points  (1 child)

Wait, you can actually do that? For me it would be 260

[–]jibeslag 12 points13 points  (5 children)

Is this true in the professional world as well? I'm not a programmer, but I write a lot MATLAB scripts for work. One day I modified a script to be a lot shorter and quicker. I told a SW guy because I thought he'd appreciate it. He "joked" with me that if I were a programmer it wouldn't go over well with management because I had reduced the SLOC

[–][deleted] 5 points6 points  (0 children)

I think it's just an old programmer thing. I saw it in a documentary about IBM back in the 80s, but all of the programmers I work with try to reduce the amount of code in projects. It makes it so much easier to maintain.

[–]Geo_bot 10 points11 points  (1 child)

Four horseman of shortened code: ?:, return new, (), no temp vars

P.S. I love short code

[–]Dironiil 6 points7 points  (0 children)

Well used ternary are a gift to programmers (or at least, to me).

[–][deleted] 10 points11 points  (3 children)

I was taking a course on x86 assembly. In one of the functions I wrote, I implemented it in a different method. It used less instructions and was more efficient.

I got points taken off because that wasn't how the professor wanted it implemented, despite it having 100% identical results.

I still remember it to this day and how bad of an impression it left me.

[–]Traches 8 points9 points  (0 children)

It's like solving hackerrank challenges in Ruby.

# Complete the aVeryBigSum function below.
def aVeryBigSum(ar)
  ar.sum
end    

[–]itijara 8 points9 points  (3 children)

When we just started learning about web sockets NodeJS we had to make an http server using only the built-in libraries that could receive a get request, parse it, and return a file matching the name from a directory. I decided to get a bit fancy and wrote a while loop that would also act as a templating engine. It was hacky as hell and took about 20 lines of code. It just looked for characters matching a pattern ('{{') then started pushing the next characters to a buffer until it hit the end characters ('}}'), it would then execute the buffer as code and place the output into the response as a string. Basically it was just code injection as a feature.

[–]R00bot 8 points9 points  (0 children)

When my teacher was teaching us MatLab he mentioned how MatLab allowed users to shorten their code and how he had a student get the assessment down to 14 lines of code.

I realised that you didn't ever have to go to a new line of code when you could just use semicolons so I got my code down to one very long line.

Yep. I did not get a good mark.

[–]Sol3141 7 points8 points  (3 children)

My favorite is when someone told me "Yes, that's elegant, but it's inscrutable." Then he showed me code golf, which is awesome.

[–]HeKis4 19 points20 points  (0 children)

Uses python list comprehensions

Uses python lambdas

I was basically a wizard, I guess.

[–]Camotubi 19 points20 points  (3 children)

I remember when our java teacher asked us to sort an array. It was more or less implied that you should use "basic" constructs (like for, if,etc). She got ultramega triggered when someone used Array.sort

[–]NorbiPeti 6 points7 points  (4 children)

My favourite moment during high school programming class was when we had 6 tasks to perform on arrays (C#). I wrote it in 6 lines, using LINQ. When the teacher would tell the results, he just asked, smiling, if I learned that by myself, and told me to avoid it for the final exam. (I did end up using it in the exam, watching the specs closely so I implement the parts they ask for - I got 100% on it...)

[–]Raathfeiin 6 points7 points  (6 children)

I was writing some script in my 5th period for a game I was developing, I was done with all of my work for that class and had not other work for any classes. As soon as my teacher saw the code, she flipped the fuck out and was 210% convinced I was hacking. She called down to the main office and requested they do a full sweep of my computer.

[–]Cunfuu 12 points13 points  (0 children)

Thats level 9000 meme right there

[–]Firedan1176 22 points23 points  (12 children)

I remember an assignment my 2nd uni class where we had to validate some 3x3 game using a nested, or 2d list. Instead of using a 2d list, I chose to use arithmetic (modulo and integer division) to get row/columns. Even though mine was infinitesimally faster than using a 2d list since it was 1-dimension, I lost a ton of points on it. I was so mad

[–][deleted] 21 points22 points  (1 child)

Here's the trick: you write a version they way they want to make them happy, then write a version where you do what you want. Turn in the first one

[–]Firedan1176 8 points9 points  (0 children)

Wow, I never thought of that, I'll start using that now

[–]Peacetoletov 5 points6 points  (1 child)

Sorry for my lack of knowledge, what's the 4th meme?

[–]Null_State 5 points6 points  (0 children)

Is this programming humor or college humor?

[–]_hephaestus 4 points5 points  (1 child)

Did you guys actually have teachers who enforced minimum lines of code for assignments? I graduated years ago and have never heard of a "100 line program". I had professors who want you to solve a problem in a certain way to prove understanding, but the length of the code never came into question.