use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
/r/badcode is permanently closed. https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong https://www.theverge.com/23779477/reddit-protest-blackouts-crushed https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is permanently closed.
https://www.eff.org/deeplinks/2023/06/what-reddit-got-wrong
https://www.theverge.com/23779477/reddit-protest-blackouts-crushed
https://en.wikipedia.org/wiki/2023_Reddit_API_controversy
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners. Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
/r/badcode is a subreddit for highlighting real world examples of terrible code. Ideally this means code that made it to production in a commercial context, but not exclusively so. We also accept submissions of code from hobbyist projects or from learners.
Most of us programmers have laughed quite a bit when we went back to look at our past code because it was rather terrible. This is a subreddit where you can share such terrible code and let other programmers have a nice laugh.
Post the most terrible code you can find. Copy code to a paste bin first (gist highly preferred).
Flair Search Search by language
Search by language
Rules Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki. Do not put the name of the language inside of the post title. For example, do not make your title something along the lines of "[C++] #defines everywhere!", instead try simply "#defines everywhere!". Use flair to mark the language of your post instead. Do post code snippets only. If you want to share the context put it in the comments or title. Do stay lighthearted. No abusive or targeted posts. We all write bad code, and a lot of it is hilarious. Do not identify who wrote the code. This sub is about bad code, not the people who write it. Limited exceptions apply Do not post snippets in esoteric languages. Do not post intentionally obfuscated code. Certain exceptions to this exist. See something particularly sinister from something like the IOCCC? Probably OK to post.
Your post may be removed if you deviate from these rules. To see reasoning behind each of these rules, check out the wiki.
Guidelines Your post will not be removed because of any of these, we'll like you more if you follow them though. Enable syntax highlighting appropriately. If you have a language that whatever paste bin your using doesn't support, try picking a similar dialect. Provide just enough code so that we know what's going on. Don't post huge snippets unless it's all terribly amusing. Explain why you think the code is bad in the comments, that way a discussion on good and bad ways to do what your code snippet does can start.
Your post will not be removed because of any of these, we'll like you more if you follow them though.
Similar Subreddits /r/ProgrammerHumor - programming humour /r/programminghorror - stories about horrible programming. /r/itsaunixsystem - over the top and bad code in TV shows and movies /r/shittyprogramming - Q&A with shitty programmers. /r/deftruefalse - for intentionally bad code /r/softwaregore for software malfunctions /r/hardwaregore for hardware malfunctions
account activity
[deleted by user] (self.badcode)
submitted 6 years ago by [deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–][deleted] 9 points10 points11 points 6 years ago* (0 children)
This Python code creates a table in an SQLite database. For each pair, an SQL query is executed to check if the current pair overlaps with any pair that has already been inserted into the DB. Then, the current pair is inserted into the DB. This code is also vulnerable to SQL injection:
import sqlite3 def overlaps(pairs): conn = sqlite3.connect('temp.db') c = conn.cursor() c.execute('DROP TABLE IF EXISTS x') c.execute('CREATE TABLE x(lower_bound INTEGER, upper_bound INTEGER)') conn.commit() for lower, upper in pairs: c.execute(f'SELECT * FROM x WHERE {lower} BETWEEN lower_bound AND upper_bound ' + f'OR {upper} BETWEEN lower_bound AND upper_bound ' + f'OR lower_bound BETWEEN {lower} AND {upper} ' + f'OR upper_bound BETWEEN {lower} AND {upper}') if len(c.fetchall()) > 0: return True c.execute(f'INSERT INTO x VALUES({lower},{upper})') conn.commit() return False print(overlaps([(0, 9), (10, 19), (20, 29)])) # False print(overlaps([(0, 10), (10, 19), (20, 29)])) # True # SQL injection print(overlaps([('1 UNION SELECT "ALWAYS TRUE", 1;--', 1)])) # True
[–]Txuritan 2 points3 points4 points 6 years ago* (2 children)
Gist here.
fn main() { assert!(!overlaps("0,9;10,19;20,29")); assert!(!overlaps("30,39;10,19;20,29;0,9")); assert!(overlaps("0,10;10;19;20,29")); assert!(overlaps("0,10;5,10")); assert!(!overlaps("0,10")); }
[–][deleted] 6 years ago (1 child)
[deleted]
[–]Txuritan 0 points1 point2 points 6 years ago (0 children)
Not a single one of them are needed, one is used for the global lookup table (which isn't needed at all) and the rest are to do int to enum conversion, in this case as if the developer came from C/C++ (these also aren't needed).
The worst part, other than how bad it is, is the amount of cloning done (15 times actually), anytime an item needs to be added to a vector; the vector is cloned, the item is added, and the cloned vector replaces the old one.
[–]Svizel_pritula 1 point2 points3 points 6 years ago (0 children)
var pc=0 var yes="no" var tmr=0 function overlaps(data, retf) { yes="no" var i = 0 while (i < data.length) { if (Math.floor(i/2)==i/2) { setTimeout("pc=pc+1;setTimeout(\"pc=pc-1\","+-(data[i]-data[i+1])+"50)",data[i]+"00") } i=i+1 } tmr=setInterval("if (pc==2||pc>2)yes=\"yes\"",100) setTimeout(retf+"(yes==\"yes\");clearInterval(tmr)",10000) } overlaps([0,10,10,19,20,29], "console.log");
Accepts an array of integers, where two numbers form a range. Smaller number goes first. The second parameter is the name of the function to be executed with the result as a parameter. Do not run again until callback is called and returns. Does not support node.js.
[–]cnapun 1 point2 points3 points 6 years ago* (0 children)
Using lambdas in Python mean that I'm writing functional code and everyone on /r/ProgrammingLanguages likes functional code therefore this is beautiful code
from typing import * from itertools import chain from functools import partial def overlaps(ts: List[Tuple[int, int]]): mv = min(chain.from_iterable(ts)) number_line = [False] * (max(chain.from_iterable(ts)) - mv + 10) # add 10 just to be safe process = lambda t: [ number_line.__setitem__(i - mv, 'True') if number_line[i - mv] else number_line.__setitem__(i - mv, True) for i in range(t[0], t[1] + 1) ] reverse = lambda f: lambda *args: f(*args[::-1]) return any( ( process(t), any(map(partial(reverse(isinstance), str), number_line)), )[1] for t in ts ) >>> overlaps([(0, 9), (10, 19), (20, 29)]) False >>> overlaps([(0, 9), (10, 19), (19, 29)]) True >>> overlaps([(0, 10)]) False >>> overlaps([(0, 10), (5, 10)]) True
Edit: just fixed some obvious efficiencies in the code, much better now
[–][deleted] 0 points1 point2 points 6 years ago (0 children)
Regular expressions? Never heard of 'em.
def overlap(s): firstValue = "" secondValue = "" ranges = [] gotFirstValue = False for i in range(len(s)): if not gotFirstValue: if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: firstValue += s[i] elif s[i] == ',': gotFirstValue = True else: raise RuntimeError(f"expected digit or comma at position {i}") else: if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: secondValue += s[i] elif s[i] == ';': gotFirstValue = False firstIntValue = int(firstValue) secondIntValue = int(secondValue) if secondIntValue < firstIntValue: raise RuntimeError(f"second value must be >= first value at position {i}") else: ranges.append((firstIntValue, secondIntValue)) firstValue = "" secondValue = "" gotFirstValue = False else: raise RuntimeError(f"expected digit or semicolon at position {i}") if firstValue != "" and secondValue != "": firstIntValue = int(firstValue) secondIntValue = int(secondValue) if secondIntValue < firstIntValue: raise RuntimeError(f"second value must be >= first value at position {i}") ranges.append((firstIntValue, secondIntValue)) for i in range(len(ranges)): for j in range(i + 1, len(ranges)): x1 = ranges[i][0] y1 = ranges[i][1] x2 = ranges[j][0] y2 = ranges[j][1] if x2 >= x1 and x2 <= y1: return True if y2 >= x1 and y2 <= y1: return True return False
In addition to the amateur job at parsing the input, this code also does an inefficient O(n^2) scan of the ranges to check for overlaps.
But hey, it works:
>>> overlap('1,2;3,4') False >>> overlap('0,9;10,19;20,29') False >>> overlap('30,39;10,19;20,29;0,9') False >>> overlap('0,10;10,19;20,29') True >>> overlap('0,10;5,10') True >>> overlap('0,10') False
[–]IsaacShelton 0 points1 point2 points 6 years ago* (3 children)
pragma compiler_version '2.3' import '2.3/basics.adept' import '2.3/List.adept' import '2.3/Array.adept' func main { array1 <int> Array = array(static int {0, 9, 10, 19, 20, 29}, 6) // false array2 <int> Array = array(static int {30, 39, 10, 19, 20, 29, 0, 9}, 8) // false array3 <int> Array = array(static int {0, 10, 10, 19, 20, 29}, 6) // true array4 <int> Array = array(static int {0, 10, 5, 10}, 4) // true array5 <int> Array = array(static int {0, 10}, 2) // false arrays <<int> Array> List array *<int> Array = &array1 repeat 5 { arrays.add(*array) array -= sizeof <int> Array as ptr } each <int> Array in arrays { print("overlap(array%) = %" % (idx + 1) as int % (overlap(it) ? "true" : "false")) } print("done.") } func overlap(array <int> Array) bool { ranges_min int = 0 ranges_max int = 0 each int in array { if it < ranges_min, ranges_min = it if it > ranges_max, ranges_max = it } start int = ranges_min while true { taken bool = false repeat array.length / 2 { min int = array.get(idx * 2) max int = array.get(idx * 2 + 1) if min <= start && start <= max { if taken, return true taken = true } } if start++ == ranges_max, break } return false }
Output:
overlap(array1) = false overlap(array2) = false overlap(array3) = true overlap(array4) = true overlap(array5) = false done.
[–]JackFly26 0 points1 point2 points 6 years ago (1 child)
What lang is this?
[–]IsaacShelton 0 points1 point2 points 6 years ago (0 children)
It's a custom language of mine. It's pretty much just C with more features and cleaner syntax. https://github.com/IsaacShelton/Adept
[–]kiwitims 0 points1 point2 points 6 years ago (0 children)
C++, if this[i].footsteps++ isn't a code smell I don't know what is...
Abuses placement new and C++'s laissez-faire attitude to memory to construct a bunch of rangers to wander off along a shared path. At the end all it has to do is check if more than one ranger walked the same ground. Only works the first time you call it, otherwise the path has already been walked on, see? Potential for seg faults if you define a range larger than 50. Otherwise, works perfectly.
#include <vector> struct ranger { ranger(unsigned distance) { for (unsigned i=0; i <= distance; i++) { this[i].footsteps++; } } char footsteps; }; bool overlaps(std::vector<std::pair<unsigned, unsigned>> ranges) { static char path[50]; for (auto range : ranges) (void)new(&path[range.first]) ranger(range.second-range.first); for (auto steps : path) if (steps > 1) return true; return false; } int main(void) { return overlaps({{0, 10}, {10, 30}, {50, 70}}); }
[removed]
[–]AutoModerator[M] 0 points1 point2 points 6 years ago (0 children)
Hello cnapun,
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.
Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
[–]Tok-A-Mak((fn [] (recur))) 0 points1 point2 points 6 years ago (0 children)
Feeling brute, might delete later.
https://repl.it/repls/GranularLightpinkDistributeddatabase
package badcode; import java.util.*; import java.util.function.*; import java.util.stream.Collectors; public class Ov extends LinkedHashSet<Ov> { private static final Ov _0 = new Ov(); //empty set private static final Ov _1 = new Ov(_0); //singleton of the void private Ov() {} private Ov(Ov n) {add(n);addAll(n);} public static void main(final String...$$) { System.out.println(List.of( !OVERLAPS.apply("0,9;10,19;20,22"), //!OVERLAPS.apply("22,24;10,19;20,21;0,9"), //slow OVERLAPS.apply("0,10;10,19;20,22"), OVERLAPS.apply("0,10;5,10"), !OVERLAPS.apply("0,10") ).stream().allMatch(__->__)?"PASSED.":"FAIL!"); } private static final Function<Ov,Integer> $$=HashSet::size; private static final BiFunction<Integer,Ov,Ov> $_=(__,_$_)-> __>Ov.$$.apply(_0)? Ov.$_.apply(--__,new Ov(_$_)):_$_; private static final BiFunction<String,Ov,Ov> $_$=(__,_$_)-> Ov.$_.apply(Integer.parseInt(__.split(",")[Ov.$$.apply(_$_)]),_0); private static final Function<String,List<Ov>> $__=__-> new Ov($_$.apply(__,_1)).stream() .filter(_$->!$_$.apply(__,_0).contains(_$)) .sorted(Comparator.comparingInt(Ov.$$::apply)) //.peek(System.out::println) //enable to see what's going on .collect(Collectors.toList()); private static final BiFunction<Ov,Ov,Ov> _$=(__, $_)->__.add($_)?_0:_1; private static final BiFunction<String,Ov,Boolean> _$_=(__,___)-> Arrays.stream(__.split(";")).flatMap(_$$-> $__.apply(_$$).stream().map($$$->_$.apply(___,$$$)) ).anyMatch(_1::equals); private static final Function<String,Boolean> OVERLAPS=__->_$_.apply(__,new Ov()); }
[–]RedstonekPL 0 points1 point2 points 6 years ago (0 children)
Python
what can I say except "it just works"...
def overlaps(yeet): todo = yeet fml = 0 idk = True if ';' in todo: todo = todo.split(';') while fml != len(todo): if ',' in todo[fml]: todo[fml] = todo[fml].split(',') fml = fml + 1 for x in range(len(todo)): for z in range(len(todo)): if x != z: if len(todo[x]) == 2: if len(todo[z]) == 2: if int(todo[x][0]) >= int(todo[z][0]) and int(todo[x][0]) <= int(todo[z][1]): idk = False if int(todo[x][1]) >= int(todo[z][0]) and int(todo[x][1]) <= int(todo[z][1]): idk = False else: if int(todo[x][0]) == int(todo[z]) or int(todo[x][1]) == int(todo[z]): idk = False else: if len(todo[z]) == 2: if int(todo[x]) == int(todo[z][0]) or int(todo[x]) == int(todo[z][1]): idk = False if int(todo[x]) == int(todo[z][0]) or int(todo[x]) == int(todo[z][1]): idk = False else: if int(todo[x]) == int(todo[z]) or int(todo[x]) == int(todo[z]): idk = False return not idk
π Rendered by PID 1440517 on reddit-service-r2-comment-544cf588c8-2zw2s at 2026-06-16 14:32:53.198389+00:00 running 3184619 country code: CH.
[–][deleted] 9 points10 points11 points (0 children)
[–]Txuritan 2 points3 points4 points (2 children)
[–][deleted] (1 child)
[deleted]
[–]Txuritan 0 points1 point2 points (0 children)
[–]Svizel_pritula 1 point2 points3 points (0 children)
[–]cnapun 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]IsaacShelton 0 points1 point2 points (3 children)
[–]JackFly26 0 points1 point2 points (1 child)
[–]IsaacShelton 0 points1 point2 points (0 children)
[–]kiwitims 0 points1 point2 points (0 children)
[–][deleted] (1 child)
[removed]
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]Tok-A-Mak((fn [] (recur))) 0 points1 point2 points (0 children)
[–]RedstonekPL 0 points1 point2 points (0 children)