for vs foreach

You may think this is a superfluous post as there are many posts on web already discussing about performance measures when using  for or foreach. Some of them are:

I would like to discuss something else here than that of performance measure. Recently while doing a peer code review I found following code snippet as a solution:
-
-
I was just wondering what this code doing for a while. Initially only optimization I could think of was to avoid executing ++secondIndex once if expression is true i.e. secondIndex will always be larger for subsequent iterations. Just after few seconds wake up signal was sent to my mind and I said, ah – this is wrong! There is another hidden loop here which is nothing but a call to IndexOf. It is a linear search over the collection and time complexity of the algorithm is O(n). Using for loop here will be much faster and much more readable.
-
-
Conclusion is that never use foreach when code inside loop have to deal with indexes.

Design Pattern: Strategy

Define

Patterns are reusable solutions to commonly occurring problems in software design. In this first article I will define and explore one of the most used patterns Strategy. The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Explore

Design Pattern Strategy

 When can I use this?

  • When dynamic swapping of algorithm implementation is required.
  • To Increase extensibility by allowing addition of new strategies.

Sum-up

This pattern is based on design principles

  • Favor composition over inheritance because HAS-A can be better than IS-A.
  • Identify the aspects of your application that vary and separate it from what stays the same.

I would like to hear from you

  • Why inheritance is less favorable in this case?

Hello!

Welcome to Coffee Time Read.

I always wanted to spent time in writing blogs on what I read during free time. My aim here is to explain complex things in simple language. Categories could be Technology, Computer Languages, Philosophy…

Happy Reading!

Follow

Get every new post delivered to your Inbox.