3 ms·
Is your method "getUserIfItExists(username)" or "doesUserExist(username)"?
by jrockway 11y ago
Is your method "getUserIfItExists(username)" or "doesUserExist(username)"?
- BorgHunter 11y agoIt's pretty common to need to do something to your user object if it does exist. As a toy example, it's far better to have something like (using Scala syntax here): def getUserGreeting(userDao: UserDAO)(username: String): String = userDao.getOptionalUser(username) match { case Some(user) => "Hello, " + user.getFullName case None => "Not logged in" } than: def getUserGreeting(userDao: UserDAO)(username: String): String = if(userDao.doesUserExist(username)) match { "Hello, " + userDao.get(username).getFullName } else { "Not logged in" } For one thing, the first function probably only makes one database call, while the second (absent caching) makes two. Secondly, the second carries with it the (unlikely) possibility that the user is deleted between your DAO calls. Thirdly, I would argue that the first function is easier to read.
- virtualwhys 11y ago2nd version wouldn't compile (need to remove "match"). probably more idiomatic for the 1st version would be: userDao.getOptionalUser(username).map(u=> s"Hello, ${u.getFullName}" ).getOrElse("Not logged in") i.e. string interpolate and map instead of match over Option.
- tel 11y agoCertainly "get". Sorry for the semantic confusion. Another word I use a lot is "lookup".