Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

kotlin - Is it considered bad convention when in iterating through two maps, I don't check if key exists in one of them?

I have two maps, let's call them oneMap and twoMap.

I am iterating through all the keys in oneMap, and if the key exists in twoMap I do something like


fun exampleFunc(oneMap: Map<String, Any>, twoMap: Map<String, Any>) {
   for((oneMapKey, oneMapVal) in oneMap) {
      if (twoMap.containsKey(oneMapKey)) {
         val twoMapVal = twoMap[oneMapKey]
         if (twoMapVal == oneMapVal) {
            //do more stuff
         }  
         //do more stuff, I have more if statements
      }      
   }
}

To avoid having more nested if statements, I was wondering if instead I could get rid of the

if (twoMap.containsKey(oneMapKey)) check. if twoMap doesn't contain the oneMapKey, we get a null object, and my code still works fine. I was wondering if this is considered bad convention though


fun exampleFunc(oneMap: Map<String, Any>, twoMap: Map<String, Any>) {
   for((oneMapKey, oneMapVal) in oneMap) {
      
      val twoMapVal = twoMap[oneMapKey]
      if (twoMapVal == oneMapVal) {
         //do more stuff
      }  
      //do more stuff, I have more if statements
        
   }
}

question from:https://stackoverflow.com/questions/65602476/is-it-considered-bad-convention-when-in-iterating-through-two-maps-i-dont-chec

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends. Do you wanna execute the "more stuff" or not?

If you do not wanna execute it you should keep the if condition. Though, if you are concerned about indentation (and deep if hierarchies) you can consider breaking out of the loop:

for((oneMapKey, oneMapVal) in oneMap) {
  if (!twoMap.contains(oneMapKey)) continue // continue with next iteration

  // do more stuff
}

If your map does not contain null values you can also get the value and check if the result was null (which means the key was not present in the map):

for((oneMapKey, oneMapVal) in oneMap) {
  val twoMapVal: Any = twoMap[oneMapKey] ?: continue // continue with next iteration

  // do more stuff
}

So its always good practice the remove useless code and (in my opinion) to have less if-hierarchies, as you can easily loose focus when you have lots of nested conditions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...