Made a quick space combat simulator a while back for some friends, and then I came back to work on it... The commit time was not, in fact, at a reasonable hour. Clearly I was trying to get it done, with no regard for maintainability. But, yes, it does in fact work perfectly.
Edit: And this isn't the only one of these, too. Great.
Simply split it out into separate lines and give names to things so you can at least see what's going on faster. No need to go any extra unless you have an actual additional use case at the time.
You need to pick up Clean Code. Needing comments is a sign the code is not quality, according to Uncle Bob. Here, for example, it's likely the case you can use variables with descriptive names to remove all the comments, e.g. ship_name = line.split(";")[0]. The bigger error is using a custom serialization technique not in the name of performance. That's about the only time you bring one of those out - when you're doing microoptimizations, because it is essential for the project (either you have a latency requirement or the savings in compute/bandwidth are big enough to justify the expense of having developers work on the problem more carefully). As a rule of thumb, you likely are not in that zone when coding in Python, because if you were, you'd have switched to a faster language by now.
I don’t remember exactly what I was doing, but I probably used a custom format for either simplicity (exactly what I need, nothing I don’t) or practices’ sake. Just recently, on a C# project I messed up serializing something because I forgot to read that generics weren’t supported but I wanted to practice using those. It’s all personal, though, so I don’t feel that bad about it all.
Man, all those values labelled with comments to describe what they're for. If only there was some kind of way to assign a name to a value such that it's easier to parse and understand. Oh well, guess this is the best we can do.
[All the code in the image is highlighted. The first line has been annotated, You, 3 months ago · StealthWIP, by the IDE. The code reads as follows:]
return Ship(
# Ship Name
line.split(":")[0],
# Ship shield, armor, and hull
[
int(line.split(":")[1].split(",")[0][1:-1].split(";")[i])
for i in range(3)
],
# Ship evasion stat
int(line.split(":")[1].split(",")[1]),
# Weapons, can be empty
[
self.weapons[str(line.split(":")[1].split(",")[2][1:-1].split(";")[i])]
for i in range(len(line.split(":")[1].split(",")[2][1:-1].split(";")))
]
# Ensure weapons list isn't empty while making original list
if (
len(line.split(":")[1].split(",")[2][1:-1].split(";")) > 1
or (
len(line.split(":")[1].split(",")[2][1:-1].split(";")) == 1
and not ("" == line.split(":")[1].split(",")[2][1:-1].split(";")[0])
)
)
# Weapons list is empty
else [],
# Defenses, can be empty
[
self.defenses[str(line.split(":")[1].split(",")[3][1:-1].split(";")[i])]
for i in range(len(line.split(":")[1].split(",")[3][1:-1].split(";")))
]
# Ensure defenses list isn't empty while making original list
if (
len(line.split(":")[1].split(",")[3][1:-1].split(";")) > 1
or (
len(line.split(":")[1].split(",")[3][1:-1].split(";")) == 1
and not ("" == line.split(":")[1].split(",")[3][1:-1].split(";")[0])
)
)
# Defenses list is empty
else [],
# Stealth factor, which will not suffice to just use an int for
int(line.split(":")[1].split(",")[4])
if line.split(":")[1].split(",")[4] != "False"
else False,
)
Just give it a try and start with simple expressions like abc(.*)def Also regex101.com can be helpful, I always paste the text contents there and inspect whether I have written the correct expression and can tweak it a little bit. It is very powerful, lately used RegEx in VSCode to edit code, that was fun, for real :D
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
In all honesty though, RegEx is great, and I don't think your code is that bad. You comment the parts that need commenting so you know what the point of the code is. It's easy to refactor if you so choose.
You don’t need to know regex in order to use it. Sites like regexr.com make it ridiculously easy to craft your own patterns with a user-friendly editor AND test them at the same time.
Source: my own experience in using regex without knowing it
Actually did this years ago on a game where we didn’t have json.. etc support. (2008 ish?)
We stored stuff like shovel:1;hammer:2; (player has 1 shovel, 2 hammers) and split on the delimiters. This was actually pretty common (CSV are super popular) as far as I know before serialization like JSON, BSON.. etc got popular. No way in hell was we touching xml
When I'm writing in other languages, I almost always go with a hard functional vs. procedural split wherever I can, even in OOP languages. I've found that OOP plus explicitly making each method either a function or a procedure has really helped my productivity -- and helped me make fewer bugs! And crapshows like this one.
Don’t pick it apart. Definitely don’t use regex. Write a grammar and visit.
The number of times I see this in production code is just astounding. Nobody can maintain it much less extend it, it’s brittle af and breaks constantly.
I think a function that takes integers as parameters and passes them to these chained splits might work better, and you could build a map for the integers to label them so it was debuggable later. I’d need the source “line” to work it out exactly
Refactor took minimal changes. Mostly just aliasing with some names:
def parse_ship(raw: str) -> Ship:
name, ship = raw.split(":")
parts, evasion, weapons, defenses, stealth = ship.split(",")
def parse_array(raw: str) -> list[str]:
without_braces = raw[1:-1]
if len(without_braces) < 1:
return []
return without_braces.split(';')
return Ship(
name,
[int(p) for p in parse_array(parts)], # shield, armor, and hull
int(evasion),
[self.weapons[w] for w in parse_array(weapons)],
[self.defenses[d] for d in parse_array(defenses)],
False if stealth == "False" else int(stealth), # False is a sentinel value, can't just use 0
)
88
u/[deleted] Apr 04 '23 edited Apr 04 '23
Made a quick space combat simulator a while back for some friends, and then I came back to work on it... The commit time was not, in fact, at a reasonable hour. Clearly I was trying to get it done, with no regard for maintainability. But, yes, it does in fact work perfectly.
Edit: And this isn't the only one of these, too. Great.
73
u/Servious Apr 05 '23
Man, all those values labelled with comments to describe what they're for. If only there was some kind of way to assign a name to a value such that it's easier to parse and understand. Oh well, guess this is the best we can do.
44
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 04 '23
Image Transcription: Code
[All the code in the image is highlighted. The first line has been annotated,
You, 3 months ago · StealthWIP, by the IDE. The code reads as follows:]I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
9
u/robottron45 Apr 04 '23
regex
2
u/DestructionCatalyst Apr 05 '23
Omg are they parsing json manually?
23
u/nykezztv Apr 04 '23
Actually did this years ago on a game where we didn’t have json.. etc support. (2008 ish?)
We stored stuff like shovel:1;hammer:2; (player has 1 shovel, 2 hammers) and split on the delimiters. This was actually pretty common (CSV are super popular) as far as I know before serialization like JSON, BSON.. etc got popular. No way in hell was we touching xml
18
u/jexmex Apr 04 '23
Pretty clean for what it is honestly.
4
u/unix_enjoyer305 Apr 05 '23
every time I do one of those split, index, split combos; I just feel soooo....naughty
4
u/pah-tosh Apr 05 '23
I love the acknowledgment that « int » will not suffice in the end…
1
u/NetherFX Apr 05 '23
This is probably the best advertisement for functional programming
6
u/MCShoveled Apr 05 '23
Imagine not knowing what ANTLR is for. 😑
Don’t pick it apart. Definitely don’t use regex. Write a grammar and visit.
The number of times I see this in production code is just astounding. Nobody can maintain it much less extend it, it’s brittle af and breaks constantly.
3
u/whoopsdang Apr 05 '23
I think a function that takes integers as parameters and passes them to these chained splits might work better, and you could build a map for the integers to label them so it was debuggable later. I’d need the source “line” to work it out exactly
3
u/No-Witness2349 Apr 05 '23
Refactor took minimal changes. Mostly just aliasing with some names:
2
u/Sweet-Ad668 Apr 05 '23
Oh well I threw up and currently walking in my own vomit
2
u/Expensive-Exercise-2 Apr 05 '23
Never saw chains of split(). Hurts a little bit 🥲
2
u/CaitaXD Apr 05 '23
Just use JSON dummy simple third party parses
1
u/[deleted] Apr 05 '23
My head hurts
1
u/nephelokokkygia Apr 05 '23 edited Apr 05 '23
If it absolutely must be a one-liner...
I did not test this code.
-11
u/inthemindofadogg Apr 04 '23
People calling things like this a one liner is disgusting. You should not be proud of this at all.