281
u/BR34D_ Apr 24 '21
This Code is screaming REFACTOR ME!
135
u/sanglesort Apr 24 '21 edited Apr 25 '21
this could be one function, like just have a tag param
edit: I am sorry for being obvious, I beg for mercy
15
u/BaconKami Apr 25 '21
And then all the functions could call that 'chosetagGeneric' method, and if you want to add a new tag you just add the function that calls it right? (I am joking of course)
5
u/5p4n911 Apr 25 '21
Honestly, I might make some stupid shorthand functions for it in some obscure place just because I am lazy to write those extra ""s
75
38
0
104
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 24 '21
Image Transcription: Code
from tkinter import *
#from tkiner.ttk import *
root = Tk()
genreMenuActive = False
selectedtags = []
def chosetagComedy():
if 'Comedy' in selectedtags:
selectedtags.remove('Comedy')
else:
selectedtags.append('Comedy')
print(selectedtags)
def chosetagFantasy():
if 'Fantasy' in selectedtags:
selectedtags.remove('Fantasy')
else:
selectedtags.append('Fantasy')
print(selectedtags)
def chosetagAdventure():
if 'Adventure' in selectedtags:
selectedtags.remove('Adventure')
else:
selectedtags.append('Adventure')
print(selectedtags)
def chosetagRomance():
if 'Romance' in selectedtags:
selectedtags.remove('Romance')
else:
selectedtags.append('Romance')
print(selectedtags)
def chosetagAction():
if 'Action' in selectedtags:
selectedtags.remove('Action')
else:
selectedtags.append('Action')
print(selectedtags)
def chosetagDrama():
if 'Drama' in selectedtags:
selectedtags.remove('Drama')
else:
selectedtags.append('Drama')
print(selectedtags)
def chosetagFamily():
if 'Family' in selectedtags:
selectedtags.remove('Family')I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
55
101
u/Big16th Apr 24 '21
I wish I knew how to code
284
u/Blackbird-ce Apr 24 '21
Just like the author of this code does
24
2
u/Own-Plantain4057 Apr 25 '21
im very new to coding ok? ;-;
3
u/Naeio_Galaxy Apr 25 '21
Yeah I understand don't worry, many of us have gone though this. What is important is to learn how to improve, learn what one should not do before doing such things in a released app. It may seem harsh at first, but really we don't hate you at all. And it's not like if it was a code on production, that might be widely used.
So it's alright. We make a bit of fun of this code and help you learn how to avoid it, and that's it 😉
2
u/Own-Plantain4057 Apr 25 '21
thanks man, dont worry i wasn't actually upset; i even provided the screenshot to my friend but this is still nice message :)
1
2
u/Suekru Apr 25 '21
Is this actually yours?
2
u/Own-Plantain4057 Apr 25 '21
yeah it is lol
8
u/Steppy20 Apr 25 '21
u/RoboticPlayer has a really good solution in one of the other threads:
def choseTag(tag): if tag in selectedTags: selectedTags.remove(tag) else: selectedTags.append(tag) print(selectedTags)So where you call those different functions, instead just call this function and give it the name of the tag as a parameter.
For example using choseTag('Comedy') instead of choseTagComedy() would have the same result but it means that you don't have to worry about making new functions to do the same logic you've already made.
As a general rule of thumb, if you're running the same code with subtle differences multiple times you can probably write a more abstract (less specific) function that you can use multiple times.
It helps reduce the length of the code whilst improving flexibility of use and can also help prevent errors made when you copy and paste the same thing and make a slightly incorrect change.
u/Naeio_Galaxy also has a very good explanation here: https://www.reddit.com/r/badcode/comments/mxlgzm/very_efficient_and_scalable_code/gvr16rp?utm_source=share&utm_medium=web2x&context=3
1
u/Suekru Apr 25 '21
As others have mentioned, just need to simplify it into one method. But other than that, I wouldn’t call it bad. Just a bit redundant is all.
21
u/devmanters Apr 24 '21 edited Apr 25 '21
Honestly, it isn't hard. Go follow a tutorial on writing some JavaScript, you need essentially no tooling and can write some happy little functions fairly quickly! It's a bit of a rabbit hole, but feel free to PM me if you have questions!
Edit: This has gotten a ton of traction!! Kudos to the guy who just said "No."
There are a lot of opinions floating around. Unless you are jumping the gun to go straight to university for programming, don't start with C. I primarily program in C++, Python, and JavaScript (specifically Nodejs).
Both JavaScript and Python are excellent for beginners. All these people with a ton of experience programming forget how unforgiving C#, Java, etc. Can be for someone totally green. I am talking about writing your first loops, hello world. Writing a script that runs infinitely and prints that your best friend is an idiot to send them a video of over social media. That is the kind of stuff that gets people to ease into it.
Regardless my offer still stands to help if you like, and I hope these goons haven't scared you off at the "choose a language to learn" step.
50
u/Tomekske Apr 24 '21 edited Apr 25 '21
No, if he wants to learn how to code he should investigate non Web languages. They're super inconsistent especially with javascript callback hell. As a starter he should focus on variables types, basic logic and some oop principles. I'd suggest C# and python. Ideally I'd suggest C but most beginners will lose interest very quickly
25
Apr 24 '21
I am pretty sure that if my first language was C# I would've never become a dev. +1 for python tho.
19
u/aaryanmoin Apr 24 '21
C# is my favourite language so I might be biased but C# is not really that hard. Sure, it's not Python, but it sure is a lot easier and more high-level than C...
8
Apr 24 '21
That's exactly the problem. It is so high level that a begginer just starting out is probably going to be confused by classes and the such. Imagine trying to explain OOP to a begginer who doesn't even know what a variable is. I know that you can ignore those things, but I feel the language is ill suited for teaching.
9
u/_advice_dog Apr 25 '21
I disagree, they often use Java when teaching beginners in school.
You don't need to jump into classes, you can just use primative types. And needing to type 'int' might be easier to understand various data types.
4
u/Suekru Apr 25 '21
Eh, I mean they used to teach students C++ for coding and now it's usually Java or Python.
My first language was C# and I honestly recommend C# as a starting language. While python is cool for quick scripts and automation and stuff I think C# gives you a better ground knowledge programming as a whole and is still pretty easy.
5
u/aaryanmoin Apr 24 '21
Ahh yes I see your point. Even if someone could understand classes fine like I did, I had a really hard time at first understanding generics and delegates and interfaces and polymorphism and... Yea maybe beginners should stick to Python.
2
u/Blip1966 Apr 25 '21
You don’t have to understand polymorphism to use C#. In fact I’d bet a large number of junior devs couldn’t tell you what it is. I always include a question about it in an interview; because it’s a useful indicator of what level of serious they are about OOP, and more importantly, if they don’t know what it is gives a good indicator of how honest they are when they don’t know something. Honesty and being able to admit when you need help or don’t know is a big positive for a new hire.
TL;DR you don’t need to understand OOP to learn to program in C#. Understanding that a variable is a thing might be useful though, especially in this code block ;)
1
u/itsTyrion Apr 25 '21
Kotlin or Java? Maybe?
3
Apr 25 '21
Java suffers from many of the same problems as C#, maybe even more so. Can't speak for Kotlin tho, as I haven't studied it.
4
u/nosam56 Apr 25 '21
My first language was Java and I think that while it suffers from the same types of problems as C#, it suffers way less. Not nearly as much worrying about nullables or delegates or operator overloading or weird syntax-breaky statements like LINQ. Java is much more barebones and I think that helps make it somewhat more learnable. As always tho I'm biased bc I dig Java
2
u/Suekru Apr 25 '21 edited Apr 25 '21
I'm opposite, but it's probably cause I learned C# as my first language and Java in college. Honestly, there's so many cases that I can write a lot cleaner and sorter code in C# than in Java. I also like being able to use 'var' as well.
But overall I just find it easier to read. For example, using the random class to spawn a number between say 55 and 121. Assuming we have the import statements in both in Java it would be
Random rng = new Random(); rng.nextInt(67)+55;while in C#:
var rng = new Random(); rng.Next(55, 122);I just find that a lot easier to read personally and it's not only the Random class, but a lot of methods in C# that just feel cleaner to read. But each their own.
Edit: Spelling and final thought.
1
u/5p4n911 Apr 25 '21
I am a Java guy and for me it's the other way around. If I see some Java code, I could probably guess what it does even without comments (rng.nextInt() returns a random int). With C# I have to look up the documentation because rng.Next() could return basically anything. Also the incoherent wrapper class naming (lowercase int instead of Integer and stuff) and the C# NeverRememberHowThisCaseIsCalled() case methods always messed up my Java code and the Java camelCase() methods messed up my C# code when I programmed C# in class for a few months.
3
u/Suekru Apr 25 '21
I suppose it’s just all about experience. At this point I’ve programmed in both pretty frequently so I can switch between pretty easy.
Personally I like the CamelCase since it looks nice to me. I lean towards C# heavily but I’m fine with both.
→ More replies (0)1
u/nosam56 Apr 25 '21
Oh for SURE C# is more elegant and easier to read, I just think that that elegance can be confusing for newcomers.
1
u/itsTyrion Apr 25 '21
yup. I actually like Java.
/circlejerk time Everybody gangster until AbstractSingletonContextWrapperFactoryVistorBuilder shows up1
u/itsTyrion Apr 25 '21 edited Apr 25 '21
Kotlin is based on, and interoperable with Java, gets rid of some weaknesses/annoying things and and adds A LOT of stuff. key things:
strong, inferred, static typing and with explicit nullability (
Int/Int?) and null-safe operators (nullableVariable?.foo()/nullableButNotNull!!.bar()). That's a big one imo, brings more compile time safetyA bit more FP while remaining OO. Lambda functions are often inlined by the compiler for better performance (someArray.forEach {} -> for-int).
Data classes. One keyword for a POJO one-liner. Just adding var/val makes constructor args a variable.
data class User(val id: UUID, var userName: String)There's also theobjectkeyword for Singletons with implicitgetInstance()Less verbosity. String templates(
"Welcome, $userName"). Implicit getters/setters.extends/implements->:.whenfor bothswitchand if-else-if-else-if-else. Default arguments. Named arguments. Coroutines.async-await. Extensions.internalmodifier (public, but only within the same module)13
u/BlatantMediocrity Apr 24 '21
It really doesn’t matter what language you start with. There’s really no wrong way to learn to program. All you’re doing is learning how to interact with a computer in a structured way. Learning JavaScript is a great idea because there’s minimal setup, there are tons of educational resources to reference, and you can get something up and running quickly.
Telling someone that the only good way to learn to program is by first applying themselves and learning ‘logic’ is nonsense. People learn to program by trying it out. It’s not rocket science.
2
u/5p4n911 Apr 25 '21
I know someone who started rocket science by trying random stuff out. Though he calculated a lot before first launch.
6
u/Naeio_Galaxy Apr 24 '21
Yeah, I like a lot JS (no hate please lol), but it's quite quirky (with its prototyped classes for instance), it's better as a second or third language. It's true that it requires no tooling, so it might be interesting for an initiation, but if you go deeper than that all its quirkiness shows up.
I'd advise Python as well, and I can't find any language that I know and that is as easy to learn as a first language. I don't know much C# btw, but I won't advise a strongly typed language as first language. I'd rather go on a weakly typed one and then learn that there are strongly typed languages and why so.
5
u/Suekru Apr 25 '21
I think C# and Java are fine as first languages. They are easier than C or C++ for sure, but still give a good grounding in programming.
I think it really depends on what the person wants to do with their skills. I'll recommend python if you want to make scripts or don't really know what you want to do with it, but if you wanted to say, make a game at some point, I'd probably say just bit the bullet and start with at least C# if not C++, because as an indie dev, making a game is difficult, so if you can't overcome learning a harder programming language, you're probably not making a game.
4
u/Naeio_Galaxy Apr 25 '21
Hey true. It is just that I got discouraged when I wanted to learn C++, although I already knew a bit of coding (I was already making Minigames on my calculator). I wanted to go too fast and ended up not liking C++. So my advice would be don't go too fast and try to skip too much steps. And I find that Python is a good fist step. (I still don't like very much C++ btw, even though I like C.)
If all you wanna do is make a game, there's the option of Unity or Unreal Engine, although I didn't try so I can't tell advice on these ones.
But in the end, we all are different and all have different paths. I would not recommend my path so I can only imagine what I'd prefer, but in the end everyone builds it's own path.
3
u/Suekru Apr 25 '21
Funny enough unity is C# and Unreal is C++
I do use unity for my game I’m developing now mainly cause I like C# better and I think unity is the better engine when it comes to 2D games.
But yeah I do agree. I think a lot of people hope into coding with a huge end goal and get overwhelmed because they didn’t realize how long the journey to that goal was gonna take
3
u/Naeio_Galaxy Apr 25 '21
Yeah but let's face it, using C# in unity is really different from C# standalone. And one can make a very simple Unity game without C#.
But yeah I agree, you still need to learn those languages in the end !!
2
u/Suekru Apr 25 '21
I wouldn’t say it’s really different, but of course working inside a game engine is going to be different than working outside of one.
I use C# outside of unity to make personal windows applications for myself and friends. Like compiling Skyrim special edition mods for a modded switch, for an example.
But I do get what you mean, the biggest difference is just working with the code updating every frame and the unity API for sure. Currently working on an indie game in unity for the past year, it’s been fun though.
2
3
u/KomaedaEatsBagels Apr 24 '21
python rocks, great for beginners!! although I had some trouble finding consistent tutorials when I was first starting out
2
u/TheUnlocked Apr 25 '21
Callback hell isn't much of a thing anymore now that we have promises, and a lot of the strange quirks of Javascript are things that many tutorials and guides will try to prevent you from using from the very start (like showing let/const instead of var).
1
u/sk8r_dude Apr 24 '21
I learned to code in html+css+JavaScript with some MySQL and PHP for 2 years before finally moving on to Objective-C. Learning objective c wasn’t that hard because I already had the logic built from JavaScript, though understanding OOP is a whole nother discussion. After high school I went to Carnegie Mellon University where I graduated with a CS degree. It doesn’t really matter which language you start with. A lot of the understanding is transferable to other languages.
1
7
u/Max5923 Apr 24 '21
if you dont know the basics at all, scratch helps break down the process of how everything works without it looking like a mess of words, and scratch also does almost all of the visuals and sound for you, so you can focus on the programming aspect more.
the next step would be doing python or c#, although your going to need to do some research on the libraries for them, unless you want to make a simple command script. c# + unity is really good for beginners.
5
2
u/Jonno_FTW shameless Apr 25 '21
If you're using a desktop. Press F12 in your web browser. Click on the console tab. Then type 1+1 and press enter. That's it, now you're coding!
1
63
u/RoLoLoLoLo Apr 24 '21
Since it imports tkinter with *, ugh, but that's another story, the functions are probably used for controls without inputs (like simple buttons).
The first immediately obvious improvement is deduplicating and outsourcing all logic into a helper function chosetag(tag) and just calling the helper with the corresponding string.
The second improvement, which a lot of beginners don't realize, is the fact that they can skip making special functions for every button by just using a lambda expression in the parameters for their buttons. So instead of action=chosetagComedy you can just use action= lambda : chosetag('Comedy')
10
u/tuckmuck203 Apr 24 '21
is it a tkinter thing that makes you use a lambda? why can't you just call it directly with action=chosetag('Comedy')
26
u/Rektedekte Apr 24 '21
If you do that, it would assign action to the result of chosetag. It would execute it. The lambda wraps the chosetag call into another function, so that it can be used as a callback.
4
u/tuckmuck203 Apr 24 '21
Oh gotcha, that makes total sense. Probably would've figured it out if I'd tried it haha. Thanks for the explanation!
2
u/Undertilted Apr 25 '21
I’m curious, what’s the problem of importing things with *? Is this just an issue with tkinter, or do you mean in general? The only thing I can think of would be that it might be confusing to see where certain methods come from, as opposed to say importing tkinter as t and doing t.func(), but I’m curious if there’s a different reason or not.
5
u/Monmine Apr 25 '21
I guess it's because it can conflict with other libraries if two identical names are found. It also makes the code harder to understand because you can't easily tell where the function was defined.
31
u/tbagrel1 Apr 24 '21
The OP seems to be using Tk to create a GUI, and I think that he/she created a function for each button/checkbox available on the GUI because Tk widgets can take a `action=<function>` parameter. A better alternative might be to create a generic `def chose_tag(tag_name)`, and use `action=lambda: chose_tag(<tag_name>)` on each button/checkbox definition. Anyway, its something quite hard to get when someone is only a beginner with GUI creation (especially in Tk)
4
17
16
u/Gaareth Apr 24 '21
I don’t want to live anymore
25
4
3
u/Naeio_Galaxy Apr 24 '21
Why ? Afraid of being implemented with spaghetti code ? 🍝 🍝 🍝🤤
(I hope you're just joking btw)
12
5
u/patrickalphac Apr 25 '21
No this is good. You just need another script that will write code as new tags are created. Then you can maintain both scripts.
Every additional line of code makes your program better. You can also brag to your friends about how many lines of code you write, that’s what really matters. Just don’t tell them your bot is writing the code.
2
u/BongarooBizkistico Apr 25 '21
How can developers possibly stand coding garbage like this? It will always being pain to you in the future... Unless you're a contractor, in which case this still makes you a huge asshole.
1
1
1
1
u/genericlifecharacter Apr 25 '21
This is like the first post where I can safely say, that’s bad code dude!
every other post makes me feel dumb as shit
1
u/Own-Plantain4057 Apr 25 '21 edited Apr 25 '21
Man I wonder who the author of such terrible code could be
Im new to coding ;-;
I figured that since the gui was having buttons for movie genres i could be lazy and do it like this cause its not like new movie genres gonna appear out of nowhere. And if they did it would only be like 1 new genre
1
1
1
u/RudyTwastaken Apr 25 '21
No like god level coder here but,
Couldnt he make it a switch case? (Match case if py 3.10)
1
1
u/AtheRipper Apr 25 '21 edited Apr 25 '21
selected_tags = list()
valid_tags = [
"Drama",
"History",
"Maths"]
def chooseTag(subject):
if subject in valid_tags:
if subject in selected_tags:
selected_tags.remove(subject)
else:
selected_tags.append(subject)
else:
passThere we go
1
u/AtheRipper Apr 25 '21
selected_tags = list()
valid_tags = [
`"Drama",`
`"History",`
`"Maths"`]
def chooseTag(subject):
`if subject in valid_tags:`
`if subject in selected_tags:`
`selected_tags.remove(subject)`
`else:`
`selected_tags.append(subject)`
`else:`
`pass`1
u/Own-Plantain4057 Apr 25 '21 edited Apr 25 '21
After looking at all the comment, my code now looks like this.
def choseGenreTag(genre):
if genre in selectedtags:
selectedtags.remove(genre)
else:
selectedtags.append(genre)
print(selectedtags)
redbtn = Button(
topframe,
text='Comedy',
fg='red',
bg='white',
command=lambda: choseGenreTag('Comedy'))1
1
u/RandomAccount4821 Apr 25 '21
I have something similar to this in my very amateur website, I’m just trying to get functionality before I refactor it all
-2
-51
u/NetherFX Apr 24 '21
Still pretty readable, and I can't quickly think of an improvement
96
u/RoboticPlayer Apr 24 '21
Just pass it as a parameter
def chooseTag(tag): if tag in selectedTags: selectedTags.remove(tag) else: selectedTags.append(tag) print(selectedTags)6
u/lizard450 Apr 24 '21
Use a hashtable would be an improvement... Or an enum bit array.
5
u/RoboticPlayer Apr 24 '21
True, but what I did is simple and it's what I thought of off the top of my head :)
2
1
u/AutoModerator Apr 24 '21
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/RoboticPlayer, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
5
u/Schlagbaum3000 Apr 24 '21
Maybe just one function taking a string? You can then create necessary functions with something like. You might then also create a list of functions from a list of possible tags.
chosetagDrama = lambda: chosetag('Drama')Possibly move the
selectedtagsinto a function parameter, too, to not rely on global variables.2
2
u/SuperPotterCrazy01 Apr 24 '21
Wouldn't a set give the same effect?
6
u/Schlagbaum3000 Apr 24 '21
No, each function removes the element if it exists in the list, a set would just do nothing (keep it in the set). This is probably to toggle the selection of tags.
6
u/66bananasandagrape Apr 24 '21
Why not do "if it's in the set, remove it, otherwise add it"?
If you're feeling slick you might even write it as
my_set = set() ... my_set ^= {"thing_to_toggle"}Maybe this person wanted to rely on the order of the tags though, in which case using a list is more understandable.
2
6
u/weezkhan Apr 24 '21
Could someone explain to me what's wrong, am a newbie in programming