I thought this was common sense. Sometimes it's just faster to do things sloppy and deal with it if it ever causes problems. Gotta keep up momentum sometimes and if it works it works.
sounds like someone has never had to deal with tech debt or legacy code. that’s a horrible way to think. sure you’ll never be perfect, but you shouldn’t aim for shit code
I think it heavily depends on the context. For things like prototypes and small projects you do just to explore a library or a certain aspect of programming, there’s a time and a place for not getting too caught up in the quality of code you have no intention to ever return to. Obviously for anything you plan to maintain, especially if you have multiple people that will work on the code, or if you have a project you’re wanting to show off the actual code for you should be more thoughtful about your code quality and design decisions. I think it’s very context-dependent.
Funnily enough that's exactly what I had in mind. I was gonna switch because I didn't know about it but by the time I'd learned trying to install it broke everything I had done already. I'll learn it in the next project but for now my game will stay with the old system.
Yes, that is bad code. I'd fire ya if I saw that. Learn structure. Learn to think in software. Be a computer. You'd see the solution if you'd practiced. Sorry for being harsh. But that's life.
Clever code isn't always industry code. There's a solid argument for getting quick code out to meet deadlines, and another solid argument for coding to the lowest level of your team. The lowest level includes future new hires, any interns that may work on your code, etc.
If this code is fireable, then your team is probably a squad of huge ego shit brains. Sorry for being harsh and all.
I get it. That's why I'm scared of medical equipment. It could be written as poorly as this sample. That code is trash. I see you don't agree but it is. My staff are truly intelligent and don't write crap. It's not easy being good. But it's critical that we are. You'll thank me in the hospital some day....
Wasnt there a gamma treatment machine that killed a bunch of people because the hobbiest programmer who did its software didnt account for the time it took for the mechanical parts to line up for a safety check, so the thing blasted holes in people. For some things, the smarter the better... and ok it's probably always smarter the better, but good enough is a thing too.
I dont work with life saving equipment though. I deal exclusively in personal projects for which I could easily download a library for and will probably never finish. One of my comments in something was, please dont touch this because I dont know how this works. But, it worked. I also found a pile of math that had multiplied by zero in it followed by a simple expression... the result of working myself to the point your just seeing what sticks, when the smart thing would be to rest. I do have a copy of teach yourself math tho. So next time I might be smarter.
I'll google it... it was the Therac-25. That Kyle Hill did a video on it.
At least you understood my reference. I really don't understand a group dedicated to bad code that says the really bad stuff is acceptable. I am genuinely surprised and very pleased that nobody here works for me...
It's not code style. It's not firing for misaligned braces. It's firing for incompetence. A lack of knowing what work product must be. What has quality and what is shit. You'd wish that your mechanic would have been fired for the equivalent error if it were your car fixed in such a way.
Huh?? The kind of guy who expects the staff to have basic insights to coding! Like a hospital who insists on following procedures and Not killing all the patients. Y'all are so soft to think that termination is not deserved from really bad work product.
I think the “I’d fire you” is what is getting you the downvotes. There are enough difficulties getting into coding especially starting out, gate keeping newbies with unhelpful criticism and expectations are not going to win you any points and if you were actually a position of management that is probably a lesson you should learn if you want to hire and keep the best
I said this precisely as a warning to y'all here that managers like me won't tolerate crappy work. I mentor the good ones and say good bye to the OP here. I would hope there are more like me who impose a standard of performance, hire to that standard, and pay for top talent. Of course there are a billion lines of bad code on Earth. I just will not sanction a single byte of it.
Well I hope you all the best. I would highly recommend not being so difficult. Grow your Junior devs with encouragement and promote a healthy work environment not a toxic one. You might have a good team but a great team is made so by their manager. Part of being a good manager is being a good person. If you are truly a manager I hope you learn this lesson sooner rather than later
I'd rather eliminate idiots from my company. Shall I really reflect on encouraging stupidity? I get that most redditors here have minimal training and are genuine hackers who don't see how bad code can create extremely bad results in the real world. I didn't say I'd kill the guy! I'd be shocked of course. But sypporting staff that don't even know they are incompetent is just not a plan for success.
I guess you could put all the key codes in a list and then do: itemSelected = keyCodes.FindIndex(kc => Input.GetKey(kc)). It's more compact but possibly harder to understand.
Seriously, iterators and "fancy" list manipulation stuff like this are so important for expressive programming. I can't stand the HOF and iterator slander in the JS community. Also, in my opinion, your suggestion isn't harder to understand except for a beginner programmer, so I would label it as better code in every respect except beginner-friendliness.
There is, especially in communities with lots of beginners, grifters and engagement farmers like Twitter. I've seen dozens of posts saying filter and reduce are overcomplicated compared to raw or enhanced loops. There's a time and a place for all of those, of course, but programming is no place for oversimplification at the cost of expression.
I've seen dozens of posts saying filter and reduce are overcomplicated compared to raw or enhanced loops.
I generally HARD disagree (and I know that isn't your opinion that they are bad, I'm just adding my thought)
Purely because the array methods, when used correctly, clearly express the goal of the loop.
reduce = taking list and trying to get a new single entity from it, can often skip to the initial ACC to see the type and then you can guess what is happening inside easily.
filter = taking a list and getting a (presumably) smaller list based on a condition, but same type.
map = taking a list and getting a list of same length with new transformed values
find = getting an item from a list based on some comparison function
etc.
Often it's the variable name it's being assigned to (and variable name of list) and the method being used and you can just know what the thing does right there.
for loops inherently lose this since the loop expression does not give any clues to what the result is meant to be, only what it is looping over.
They can often perform better (the for loops) especially compared to chaining array methods, but I find them FAR less expressive even with the additional code they require.
Mostly complaining about Rust with that one. Although I suppose it applies to python too. Definitely don’t mind the lack of an increment operator if there’s also no +=.
And for the record I don’t think it’s wrong or bad for those languages to not include them, I’m just used to C-like syntax.
When I say "oversimplification at the cost of expression", I mean that an implementation can be simpler without doing a better job of getting across the reasoning and purpose behind the code. In OP's case, for example, I don't think a long chain of ifs does a good job at that. What they want the code to do is: "translate the pressed number key into a zero-based index". In my mental model, that means the keycodes form an array, and the code should translate the key code to an array index. itemSelected = keyCodes.FindIndex(kc => Input.GetKey(kc)) expresses that perfectly and briefly.
Performance is pretty much an independent variable from expressiveness and simplicity. While complex code is sometimes slower, certain optimizations can themselves introduce complexity. Likewise, making code more expressive may make it faster, slower, or make no difference at all. The rule of thumb is to avoid prematurely optimizing code, and to focus on good baseline engineering practices (elegance, maintainability, understandability, conciseness, expressiveness, documentation, etc.) until you can prove a need for optimization. Good developers can recognize performance tradeoffs in the design and implementation phases, too, so there's a line to be drawn between good, performant code and aggressively/purposefully optimized code.
where does performance enter this discussion? are they equivalent?
The basic rule to follow is prefer clearness and simplicity in your code as long as performance isn't a requirement. The saying is premature optimization is the root of all evil, because when people start optimizing, they generally write more code that is more complex. More things are assumed to be true. There's more chances for bugs.
Let's take a really simple example. You have bunch of items and you want to see if one is in that bunch. Well, the simplest and surest way to handle that would be to look through everything to see if any item is the one you are in search of. It is insanely easy to understand and insanely simple to write. Now, let's say you start using relationships between your items, any two of them, any three of them, all of them together, etc. You start doing more things, storing stuff in different ways, and using an overall more complex algorithm. In this case, if your items are numbers, it's not too big of a deal to sort and do binary search since those functions are written for you and understood by everyone, but the point still remains. Imagine if you had to custom write all that stuff. There's more complexity, more chances for bugs, etc. compared to a simple linear search.
It's all about money. Simpler code with fewer bugs that's faster to write is good for reaching business goals, earning more money. So is running your code on less expensive hardware due to high efficiency and thorough optimizations. These two goals are at odds with each other. A lot of companies choose a reasonable middle point where they use slower, simpler languages (compared to C/C++/Rust) while demanding some intelligence in your algorithms but also actively dismissing any attempts at things that ugly the code for no real monetary gain in terms of hardware/bandwidth costs. Or at least not enough to add mental overhead for everyone ever who needs to look at / understand / change that code. A common example is most code shouldn't be doing sweet bit hacks. It's just too low-level and not expressive of intent. If you want to have a representation of a set, for example, use a damn set except in the most performance-important applications there are. Don't use an integer and flip bits to represent things are there. That is a nightmare to work with. It pollutes throughout your entire codebase.
There are cases where the cost of hosts is so large due to scale that it is justified to pay more money for more complex code to be written more slowly and with more risks of bugs and security issues in the name of efficiency. Or cases where something is so inefficient it doesn't finish running in time. Or cases where there are latency requirements on a service or piece of software (e.g. real-time programming must deliver its output always in a known timeframe. They can't even use allocation there since that can have variable runtime based on the operating system / what is going on. An example of that is audio-processing equipment where a delay will result in a sound artifact).
It's tough to describe, but it falls into the category of you know it when you see it. You hear of the general idea from a person like me, it makes sense to you, and you start applying it to the best of your ability. Hardware is pretty damn cheap these days while software developer salaries are pretty damn big. That means most coding out there will be leaning more toward clear/simple/slower/faster to write/safer/fewer bug code instead of blazingly fast, highly tuned, incredibly complex code.
I think most use it to mean making it clear what the purpose of the code is, and ideally with as little code as necessary to do so. Inherently, longer code, code that does more stuff, or even just a code structure that looks very similar even when it is doing a different thing, is quite a bit less expressive. It takes reading MORE to understand the goals.
So a for loop can do everything the array methods do, of course (they likely do so under the hood). But the forloop itself looks almost exactly the same when you look at doing filtermapreduce as far as the structure is concerned, and then understanding what THIS for loop does requires really looking at the block and figuring out what it does just to understand the basics of the output.
While the array methods tell you immediately what the code block is supposed to be doing (provided the person isn't using them wrong). So you end up not needing to even LOOK at what the function being used is to understand what the goal of the code is.
So I would consider the array methods more expressive. Just the part of const availableItems = item.filter(.....) tells you everything you need to know about what is happening here.
Meanwhile a for loop might seem similar
const availableItems = [];
for (const item of items) {
//...
}
This, for starters is more code and even with the for .. of it is more expression than the wild index based loops so many people do, we can't be as immediately sure that availableItems is full of elements of the same type as item (typescript does help give it clarity). Maybe it's items from within the item and not exactly the items themselves? And over time, we know requirements change and such, and this same for loop might suddenly have other logic put into it to transform the items or adjust them without the names changing.
If the enumerator key starts at 0 (most do by default), you can just pull the value from the enumerator value and new query syntax need be involved at all.
I wish they just passed the raw scancodes or smth like that, maybe the ascii value (maybe utf-8 to include international keyboards), but idk if that’s even possible in user space unfortunately
KeyCodes are an enum type, from 48 (Alpha0) to 57 (Alpha9). You could run a for loop through the 0 - 9 keys and then assign the value to itemSelected:
Input.GetKey(KeyCode.Alpha0 + key)
You would have to do a bit of conversion in your case to make the item selected to match the visual layout of the keyboard (key 0 = 9). This is the only line that doesn't seem very clear. You could probably make it more verbose but:
not any more readable than a switch statement, or even better switch expression. the switch would probably be optimized into a jump table by the compiler, too. real life performance gains may or may not be detectable depending on the context. typically input is polled every frame in a unity game though, or else the player may be smashing a button and the game doesn't detect it. if i were reviewing this code, i would definitely bring this up.
Oh for sure i agree, switch is miles better. Its just i dont think this is completely awful. Though id also be a tad surprised if the if stmt version wasn’t also optimized into a lut :P
Much better than Java. Java would just break down the JVM and dump the memory onto your harddrive. If that is a tiny docker container, it just completely obliterates any rescue attempt.
Well the regular c# int.Parse() method throws an error if it fails but int.TryParse() uses an output parameter that remains uninitialized if it fails and returns a boolean. I can then just return -1 in my method if the boolean is false.
The enum is for every possible key, i need a number from one to 9. Additionally i use -1 as a stand in for having no item selected. I settled on a solution using the raw string input parsed to an int.
It sometimes comes from code request growth in that you only wanted the 1 and 2 keys pressed at first but suddenly you need to press 3 so rather than arse around and possibly break it you just extend it a bit and thus the problem of rewriting and putting off the rewrite until the next 20 changes have come in and you have a better understanding of how stupid the users are.
I'm going to go against the grain and say the code is fine. If I made a sufficiently complex dictionary or switch statement it would be the same number of lines as your code if I wanted it easy to read, and let's not forget C#'s incredibly gross treatment of switch flow through, historically we had to use I kid you not goto statements in our switches.
The problem is the approach. GetKey is meant to return true when a named key is pressed. Here's the thing. If you want the player to be able to remap their controls in the game - and you're making a good game so this is the case - the KeyCode is going to be unpredictable at this stage of the program.
So my suggestion, instead, is to make an enum for the various things you want with names that make sense, MOVE_FORWARD, MOVE_BACK, this will limit one action per key being an enum, then make a dictionary with enum values as keys and KeyCode as values, and then populate this dictionary with default values.
Then in your dispatcher method, you can even keep it if/else and just return the result of whatever handler
public async Task<WhateverIDontCare> dispatcher(Dictionary<ActionsICareAbout,KeyCode> keyMap) {
try {
if (Input.GetKey(keyMap[ActionsICareAbout.MOVE_FORWARD])) {
Not to my knowledge, if there was one that gave a keycode i could do it more easily. Ideally there would be one tht returns a char of the key that is being pressed right now, which i could turn to a string and use int.Parse() on
I think the reason why they want you poll individual keys is because keyboards have N-key roll over and you can actually have many keys being pressed at the same time. IE how do you go diagnol with left + up if you only get the key being pressed.
I guess they could just give you a list of all keys being pressed (thats what I would prefer).
I may only be an amateur on this or uninformed and not quite know what you’re working with, but I’ve seen code similar to this is C++. On a game in a programming class that we used and altered for projects and in order to learn better programming. That program used a switch statement in the very same situation very well. By what I’m seeing, this looks like you’re using this if-else ladder for keyboard input like the game I practiced on used the switch statement. Given that I’ve seen better code myself IN A CLASSROOM SETTING WITH A HARDER PROGRAMMING LANGUAGE. Use a friggin’ switch statement at the very least.
393
u/pittybrave Mar 26 '23
if you ever feel dirty for writing code a certain way, there’s probably a better way
220
u/PooSham Mar 26 '23
I guess you could put all the key codes in a list and then do:
itemSelected = keyCodes.FindIndex(kc => Input.GetKey(kc)). It's more compact but possibly harder to understand.53
u/TheSapphireDragon Mar 26 '23
Unity's input system is a pain in the ass.
62
u/thanthemannn Mar 26 '23
KeyCodes are an enum type, from 48 (Alpha0) to 57 (Alpha9). You could run a for loop through the 0 - 9 keys and then assign the value to itemSelected:
Input.GetKey(KeyCode.Alpha0 + key)You would have to do a bit of conversion in your case to make the item selected to match the visual layout of the keyboard (key 0 = 9). This is the only line that doesn't seem very clear. You could probably make it more verbose but:
itemSelected = (i + 9) % 10The complete function:
39
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 26 '23
Image Transcription: Code
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!
10
u/OkUnderstanding1278 Mar 26 '23
Switch expression or dictionary would be better. E.g See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
public static Orientation ToOrientation(Direction direction) => direction switch { Direction.Up => Orientation.North, Direction.Right => Orientation.East, Direction.Down => Orientation.South, Direction.Left => Orientation.West, _ => throw new ArgumentOutOfRangeException(nameof(direction), $"Not expected direction value: {direction}"), };
8
u/I_DontUseReddit_Much Mar 27 '23
According to https://github.com/needle-mirror/com.unity.tiny/blob/master/Unity.Tiny.Input/Input.cs,
Alpha1-9are just names for the numbers49-57. You could try using theInputDataclass'skeysPressedorkeysJustDownlists, and do something like:21
u/DevilStuff123 Mar 26 '23
Honestly to me it’s not the worst thing in the world. Instantly readable.
6
u/Terranaform Mar 26 '23
Minecraft type beat
1
u/TheSapphireDragon Mar 27 '23
Update: I found the function that gives a raw string from the key being pressed and parsed that to an int, reducing this to four lines of code.
1
u/giantvar Mar 26 '23
I will find you…
1
u/TimelessTrance Mar 26 '23
Does Input not have a bit mask of all the currently pressed keys?
1
u/BlurredSight Mar 27 '23
This is just the Minecraft source code
1
u/TechnicalPotential23 Mar 27 '23
WHY DID YOU DO THIS IN THAT WAY!!!!!!
1
u/ElGuaco Mar 27 '23
Why are using an integer to store the selected item if you already have an enum type for it?
1
u/ouaqaa Mar 27 '23
if it's stupid and it works, it's not stupid
1
u/abdellatif-dev Mar 27 '23
My brain hurts
1
u/[deleted] Mar 28 '23
Who did this shit? Fess up now.
1
u/fliguana Mar 26 '23
Couldn't you do it in a loop?
4
u/CaitaXD Mar 27 '23
Wanna feel real dirty? here
(int.Parse(keyCode.ToString().Replace("Alpha","")) + 9) % 10
2
u/siammang Mar 27 '23
This is the way
The alternative would be using reflection, which is probably not much better.
2
u/LobotomizedThruMeEye Mar 27 '23
Store alpha in an array, set the value of itemSelected to the value of alpha, all within a for loop. Bingo bango bongo, caveman stuff, yk?
1
u/DaringCoder Mar 27 '23
for (int i = (int) KeyCode.Alpha0; i <= (int) KeyCode.Alpha9; ++i) { if (Input.GetKeyDown((KeyCode) i)) { res = i - (int) KeyCode.Alpha0; break; } }
1
u/Pleasant-Dogwater Mar 27 '23
wow clean
1
u/[deleted] Mar 27 '23
It sometimes comes from code request growth in that you only wanted the 1 and 2 keys pressed at first but suddenly you need to press 3 so rather than arse around and possibly break it you just extend it a bit and thus the problem of rewriting and putting off the rewrite until the next 20 changes have come in and you have a better understanding of how stupid the users are.
1
u/[deleted] Mar 27 '23
Emmmm....
1
u/ABoxOfFoxes Mar 27 '23
Y'all, what are you talking about? Custom iterators?? Casting keycode chars to int???
Please, just use a map and loop over the entries, please
1
u/[deleted] Mar 27 '23
There's nothing bad about this. You can feel quite accomplished, in fact:
1
u/kireina_kaiju Mar 28 '23 edited Mar 28 '23
I'm going to go against the grain and say the code is fine. If I made a sufficiently complex dictionary or switch statement it would be the same number of lines as your code if I wanted it easy to read, and let's not forget C#'s incredibly gross treatment of switch flow through, historically we had to use I kid you not goto statements in our switches.
The problem is the approach. GetKey is meant to return true when a named key is pressed. Here's the thing. If you want the player to be able to remap their controls in the game - and you're making a good game so this is the case - the KeyCode is going to be unpredictable at this stage of the program.
So my suggestion, instead, is to make an enum for the various things you want with names that make sense, MOVE_FORWARD, MOVE_BACK, this will limit one action per key being an enum, then make a dictionary with enum values as keys and KeyCode as values, and then populate this dictionary with default values.
Then in your dispatcher method, you can even keep it if/else and just return the result of whatever handler
public async Task<WhateverIDontCare> dispatcher(Dictionary<ActionsICareAbout,KeyCode> keyMap) {try {if (Input.GetKey(keyMap[ActionsICareAbout.MOVE_FORWARD])) {return await onMoveForward();}if(Input.GetKey(keyMap[ActionsICareAbout.MOVE_BACKWARD])) {return await onMoveBackward();}}catch (KeyNotFoundException) {}return NO_ACTION;}1
u/sanderthekid Mar 28 '23
Yea same do this too
1
u/Sweet-Ad668 Mar 31 '23
There’s probably an offset that could be used to set itemSelected with Keycode no?
0
u/Hinep75 Mar 27 '23
Bruh is this yandere simulator code reference.
0
u/ososalsosal Mar 27 '23
Cast that enum as an int and assign it to itemSelected
-3
u/[deleted] Mar 26 '23
Use a switch statement at least....