Which is better? ```// 1 val h = hour.toInt() + if...
# codingconventions
e
Which is better?
Copy code
// 1
val h = hour.toInt() + if (meridian.isNotEmpty() && meridian[0] == 'p') 12 else 0
or
Copy code
//2
var h = hour.toInt()
if (meridian.isNotEmpty() && meridian[0] == 'p') h += 12
1️⃣ 3
c
Copy code
val h = hour.toInt() + meridian.toOffset()
fun Meridian.toOffset() = if(firstOrNull() == 'p') 12 else 0
If
Meridian
is actually a
String
make sure that the extension function is private, better yet I suggest using a wrapper class instead of
String
for better typesafety.
e
Thanks, @Czar!
meridian
(since renamed to
period
) is returned from
MatchResult.destructured
. It’s for either AM or PM.
c
I see, then
val h = hour.toInt() + if (period.firstOrNull() == 'P') 12 else 0
would be my favourite. That said, midnight can be represented as 12 AM, and noon as 12 PM so this algorithm will return 12 for midnight and 24 for noon, I somehow doubt that that is the desired behaviour...
e
@Czar Thanks, I realized that the code has problems. My current version checks if
h < 12
before adding. Technically, 12 AM and 12 PM don’t exist and should be 12 midnight and 12 noon (respectively?). I’m planning to have a separate regex.
c
Yeah, but real world, heh 🤷‍♂️
😀 1
e
Our work sure would be easier without users.
c
😄 definitely. Interestingly if you check the link I've posted, even some dictionaries mention 12 AM meaning midnight and 12 PM meaning noon, so it's kinda not users' fault it's natural language... It's always hard to process...
e
Since 12 + epsilon PM is afternoon, it’s understandable that people consider 12 PM to be noon.
c
That's exactly how I'm remembering it 😄 Those exercises with calculations on floats and doubles are paying off in everyday life 😄
e
😃 1