Well at least for Java it seems to work just fine, however the Javadocs warn about using a locale like Turkish where "i" becomes an uppercase dotted "İ".
But with toUpperCase you only have to check one case because well, there are only uppercase letters and you dont get an error if for example someone writes rEstaurant.
If you cast it to uppercase you don't need the switch case at all, you can just cast it to upper case and use the cat directly, validating with an is in list check at the end. So the whole thing becomes two lines.
The cat is assigned a (presumably global) constant, not a string. I don't see how you can do that in one line unless you use some hacks a la "ok Compiler, insert the variable with this name here, now the string".
Or maybe I'm just misunderstanding something here. Could you show the two lines you have in mind?
If we're normalizing text, we don't care about characters that only have one variant. That's the whole point of normalization, to ensure that characters which have more than one form are in a specific, known form. From the perspective of case normalization, there's no difference between a character that only has an upper case variant and a character like $ or %; both just won't be affected by toUpper/toLower.
And it especially makes no difference in this case, where the only valid strings are exclusively made up of ASCII letters.
Converting to Unicode uppercase isn't roundtrip safe either, though. The classic example is ß -> toUpper -> SS -> toLower -> ss.
It looks like that rule is specifically intended for C#'s invariant culture casing algorithm, which leaves ß unchanged. JavaScript fully implements Unicode uppercasing/lowercasing.
The default Unicode uppercasing rules still use "SS", as explained in Unicode 5.1.0 (the version that added capital sharp S):
In particular, capital sharp s is intended for typographical representations of signage and uppercase titles, and other environments where users require the sharp s to be preserved in uppercase. Overall, such usage is rare. In contrast, standard German orthography uses the string "SS" as uppercase mapping for small sharp s. Thus, with the default Unicode casing operations, capital sharp s will lowercase to small sharp s, but not the reverse: small sharp s uppercases to "SS".
There are characters in unicode which don't have a lower letter
Given that they are apparently translating to an enum, I wouldn't expect fancy unicode to come into play. Not following capitalization rules for an enum, that I can let pass, but using eldritch unicode sigils, that deserves a visit from Yog-Sothoth.
It still raises a lot of questions about code structure though. The use cases for this approach are very limited and usually rely on well formatted input data (i.e. read a well-known value from a DB/file that has been put there from code as well), not some obviously unsanitized crap.
(Also, returning null may raise further issues with the calling method. Better define a default/unknown value and work with that)
Lawful => the syntax is OK (can compile, abides the laws) :-) Evil => what you said. Coming from some time deep into Kotlin I stopped caring about the NPE, so didn't think of it.
Still, I would prefer rethrowing a specific exception instead of returning a default or unknown (this is literally null) value when parsing unexpected input.
For that you could just throw the IllegalArgumentException from the valueOf method. Can do if you want the client to see technical information. Most of the time however it's about "sorry, unknown value entered" and especially if you're in an i18n environment, that's a lot easier to handle from an enum that just relays its property key for the label. Also, exception handling is rather costly, so rethrowing the exceptions may be a big impact on runtime.
Still I feel it's sort of bad design to have some user input convert into an enum. If you're in a forms/webforms app you can just use comboboxes with the actual enum as value and a label for display.
I almost exclusively use the valueOf method for configuration files or database value parsing where I know I can trust the input - because my app has put it there in first place.
The kind of programmer who writes this code is the kind who will individually add 100 out of the 1024 permutations, each time thinking "there I fixed it."
AI researchers and philosophers spend a lot of time trying to define what consciousness and self awareness are. I'm convinced once we define it we'll discover not all humans pass the bar.
No no no, you should iterate over the string, take the ASCII value of each character, and add 0b100000. Leave the function name as-is. Also add no comments.
I've just seen this today at work. It was a little different though. The word to be permutated was an abbreviation with only three letters (thank god).
There was an array containing every permutation and a function that checks if the array contains the given string...
I remember in a C++ course asking a classmate why all his variables were only 2 or 3 characters long. He said "my fingers get tired typing out long variable names". 😐
Some dude thought it was fine to call some functions and clases like OrderCre8 and you can't image how much I hate this person, that I've never met and never will because he doesn't even work there anymore. The thing is, a lot of pocos use this kind of contraction for the word create, and we can't change this names anymore, is in production and we would have some clients having to adjust this, fuck that guy and the ones letting that to get to production
Well, it's already there in the type. Might be an unpopular opinion but I'd rather see Category c than Category category, that feels like noise to me. You should be using an editor that can mouse over the identifier and tell you what it is.
Edit: I do think the function itself should be called parseCategory.
But imo, you should separate types from instances by upper/lowercase. Category category is a lot more readable than Category c. If I read a random line of code where something is done with c/cat/category, I have no idea what c or cat means, and it'll take more time to get into the code base. If you work in a code base of thousands of files, you're not going to be familiar with every function you have to read code in, and quickly understanding the context will be infinitely easier if it's written as close to English as possible.
Mousing over things is not something you should be required to do to read and understand code.
It's fine for peeking at another function definition, but relying on tooltips to make the code readable sounds horrible to me.
It's like reading a book where all the words are redacted to just their first letter, each with a reference to the bottom of the page where the full word is written. You'd just be looking up constantly. Mouse hover is not much more convenient.
I can get why some people don’t like it. Maybe someone on the team is using an older editor that doesn’t have auto complete? But I use really strong variable and function descriptions as names. My goal is to have the mother function read as much like a book as possible.
Then tell him he should either learn how to use Emacs (because it does support autocomplete), or switch editor to one he knows how to use.
The whole point of old editors like Vim and Emacs is to minimize number of keystrokes, so if he can't achieve that, he's doesn't know how it's supposed to be used.
In some cases shorter variable names can be easier to read, especially if no information is lost, and using longer names would necessitate more newlines (looking at you, flake8). Having said that, I'd prefer category over car as well.
Also, "parseCat" is not a great name. The abbreviation saves almost no time in typing and is confusing when not familiar with the codebase/domain. I immediately started thinking about kittens...
You can even have code in between them. The trick is that without break at the end of the case it just seamlessly continues to the next line of code, skipping any other case labels.
Kind of reminds me of code I saw from students who had taken a Haskell course the sem before taking a Java course. A bunch of cases where using a function or a basic loop would have been the normal way to perform a function it but instead they listed out case statements.
Pretty sure the nice answer here is a good old Map... Hash, Tree, whatever. Just map each ENUM to it's lower cased equivalent. This whole function is pretty much the reason maps exist, they're arrays with a nice function to convert random input into array indices. Heck, even arrays are designed to make it so that you don't have to check if 1==i, 2==i, 3==i, and so on just to get the ith element of your array.
i dont why you guys are suggesting to lower case when they clearly just need to do uppercase, then check if its one of the three words, if yes return else throw err.
Do not get it at all. What class is Category? What this has to do with lower case? Why would you not use c# instead? Has so much to offer for string checking.
If he'd call toLowerCase() he'd just need to check for the words written in lower case in the switch statement and not for 3 different ways to write a word (while forgetting the 1000x other ways someone could type the word).
In addition to the obvious point others made, you also can't just switch programming language for a most likely large project just because you like its string operations.
82
u/[deleted] Sep 02 '21
.toUpperCase()*
11
u/MyAntichrist Sep 02 '21
The nice and easy way:
.toUpperCase()The chaotic evil way:
439
u/Grubzer Sep 02 '21
//TODO add cases for all letter permutations
126
u/[deleted] Sep 02 '21
"REstaurant"
48
u/AlwaysNinjaBusiness Sep 02 '21
Also, why would you abbreviate it to "cat" instead of just writing "category"?
26
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 02 '21 edited Sep 02 '21
Image Transcription: Code
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!
13
u/Coded5 Sep 02 '21
“ReStAuRaNt”
8
u/stahkh Sep 02 '21
Also, "parseCat" is not a great name. The abbreviation saves almost no time in typing and is confusing when not familiar with the codebase/domain. I immediately started thinking about kittens...
7
u/AlwaysNinjaBusiness Sep 02 '21
"Switch statements are super useful",
"You mean like this?"
"Well yes, but actually no"
4
u/Fenxis Sep 02 '21
Also ... No exception for the error case so GG on the Random NPE that will pop up later.
4
u/[deleted] Sep 02 '21
Do all languages have "tolowercase" and "touppercase" utilities?
3
u/gabbagondel Sep 02 '21
maybe the input for catStr is more restrictive than we think.
and maybe catStr really does refer to cats. who knows really
3
u/keethraxmn Sep 02 '21
Maybe they want to only include ones with some sort of sensible capitalization ;)
That way they can exclude fat fingered typists like me.
4
u/Yangishrobin Sep 02 '21
Because I write all my code in Java....this fucking hurts...
2
u/jadenadams Sep 02 '21
Wait you can do multiple cases on one? My whole life. Fuckkk
2
u/Anonymous_Bozo Sep 02 '21
2
u/deniercounter Sep 02 '21
I don’t believe that these code snippets are real ones.
2
u/gravitas-deficiency Sep 02 '21 edited Sep 02 '21
or just:
or without try/catch:
2
u/[deleted] Sep 02 '21
hOSpiTal
“Shit why is it returning unknown category????”
2
u/CaptSzat Sep 02 '21 edited Sep 03 '21
Kind of reminds me of code I saw from students who had taken a Haskell course the sem before taking a Java course. A bunch of cases where using a function or a basic loop would have been the normal way to perform a function it but instead they listed out case statements.
1
u/eternityslyre Sep 02 '21
Pretty sure the nice answer here is a good old Map... Hash, Tree, whatever. Just map each ENUM to it's lower cased equivalent. This whole function is pretty much the reason maps exist, they're arrays with a nice function to convert random input into array indices. Heck, even arrays are designed to make it so that you don't have to check if 1==i, 2==i, 3==i, and so on just to get the ith element of your array.
1
u/abhi307 Sep 02 '21
I See You're a Man of Culture As Well
1
u/WpGgs Sep 02 '21
Just add all variants in a hashmap. /s
1
u/[deleted] Sep 02 '21
umm... always normalize toUpper, you philistine
1
u/cienciacomenta Sep 02 '21
You should loop through the string and check letter by letter of it is either lower or uppercase correct. Much simpler than this fancy "to lowercase"
1
u/AL1L Sep 02 '21
Or just make an Enum and do .valueOf and .toUpperCase
1
u/ekolis Sep 02 '21
But what if the user is Turkish?
1
u/[deleted] Sep 03 '21
reminds me of the time I forked a String.prototype.toLowerCase gist
1
u/Jonakss Sep 03 '21
Yo miss resTauratn
0
u/Sigiz Sep 02 '21
i dont why you guys are suggesting to lower case when they clearly just need to do uppercase, then check if its one of the three words, if yes return else throw err.
-1
u/FlamboyantApproval16 Sep 02 '21
for loop is also possible TBH.
0
u/KenaDra Sep 02 '21
Regex one-liner for any case...
-7
u/Celtic_Spirit Sep 02 '21
Do not get it at all. What class is Category? What this has to do with lower case? Why would you not use c# instead? Has so much to offer for string checking.
0
u/[deleted] Sep 02 '21
[deleted] — view deleted comment