Skip to main content

C# 2.0 - Iterators

Hoje vim para falar de uma das features mais úteis do C# 2.0, mesmo que muitas pessoas não saibam do que se trata. Vamos falar de iterators!

O que é um iterator?
Para quem ainda não sabe o que é o padrão iterator, podem ler a sua descrição aqui. Um iterator é uma classe/objecto que sabe como percorrer uma estrutura. Portanto, se tivermos uma lista de objectos, um iterator teria o conhecimento de como percorrer essa lista e aceder cada elemento da lista. O iterator é um design pattern bastante conhecido e está por trás de muitas coisas fantásticas que temos hoje no .NET. (assim de repente lembro-me de LINQ). A Microsoft definiu duas interfaces para este design pattern chamadas IEnumerable e IEnumerator. A primeira é implementada no objecto que vamos percorrer, a segunda é no objecto que irá percorrer o primeiro.

Porque é que é uma feature?
Diga-se de passagem, os iterators são um conceito bem conhecido mesmo antes do .NET existir. Sendo um design pattern de programação orientada a objectos faz com que possa ser utilizado em qualquer linguagem deste paradigma. A classe iterator tipicamente tem alguns métodos, por convenção. Para implementar o iterator no .NET 1.0 teríamos que implementar a interface IEnumerator. Depois, na classe que precisa de ser percorrida, teríamos de implementar a interface IEnumerable que tem um método que devolve uma instância do iterator. Será mais fácil vermos o seguinte exemplo:


No exemplo acima podemos ver que a classe Caixa implementa a interface IEnumerable e o seu método GetEnumerator devolve uma instância da classe IteratorCaixa. IteratorCaixa implementa a interface IEnumerator e recebe a variável itens no construtor. Esta é a classe que sabe como percorrer os itens de uma caixa, e desta forma podemos devolver quantos iterators quisermos através do método GetEnumerator. Por outro lado, também nos permite fazer isto:


Reparem como podemos utilizar a instância de Caixa no foreach. Internamente será chamado o método MoveNext da classe IteratorCaixa(devolvido pelo GetEnumerator), convertida a propriedade Current para string e atribuída à variável item em cada passagem. Obviamente que isto nos irá mostrar os itens da nossa caixa.

Portanto, onde está a melhoria? Já tínhamos isto antes!

A resposta está na palavra reservada yield. Agora podemos construir um iterator sem implementar a interface IEnumerator! Vejamos o código abaixo:

O snippet acima faz exactamente a mesma coisa que o primeiro, mas vejam como não foi necessário implementar a interface IEnumerator para ter o mesmo resultado. Isto representa uma poupança de tempo enorme em comparação com o código do .Net 1.0. Mas qual é exactamente o papel do yield? Reparem que de cada vez que o método GetEnumerator é executado, yield grava o estado da execução do método e vai executar o código a partir de onde ficou gravado na próxima chamada ao método. Podem tentar com o debugger e verão que a execução do método é pausada ao chegarmos à palavra yield. Podemos implementar múltiplos métodos que iterators e depois utilizá-los explicitamente no foreach.

Para sair do ciclo, podemos utilizar a palavra yield break no método GetEnumerator e o ciclo acabará ali. Um iterator pode ser utilizado no getter de uma propriedade e terá os mesmo efeitos. O tipo que um método iterator devolve tem que ser IEnumerable, IEnumerator, IEnumerable(T) ou IEnumerator(T). Poderia ter utilizado as interfaces genéricas no post, mas achei melhor não misturar generics e iterators para não confundir o leitor.

Quando precisamos de percorrer uma estrutura de uma forma diferente, é sempre boa ideia implementar um iterator. Eu nunca precisei de fazer isto porque a grande parte das estruturas que utilizo já implementam o IEnumerable, e para algo mais complexo posso utilizar LINQ, mas no C# 2.0 não tínhamos ainda esta evolução e havia mais espaço para iterators.

Este é um tópico um pouco confuso e é fácil perder o fio à meada. Caso hajam dúvidas sobre o assunto deixem comentário, porque eu próprio me lembro de ter alguns problemas em compreender esta matéria no início.

No próximo post irei traduzir o artigo sobre Classes Parciais no Run or Debug.

Comments

Popular posts from this blog

From crappy to happy - refactoring untestable code - an introduction

I started testing my code automatically a couple of years in after starting my career. Working in a small company, there weren't really incentives for us to automate testing and we were not following any kind of best practices. Our way of working was to write the code, test it manually and then just Release It ™ , preferably on a Friday of course. I'm sure everyone can relate to this at some point in their career, because this is a lot more common than the Almighty Programming Gods of the Internet make us believe. I find that the amount of companies that actually bother writing tests for their production code is a fraction of the whole universe. I know some friends who work in pretty big companies with big names in the industry and even there the same mindset exists. Of course, at some point in time our code turned into a big pile of shit . Nobody really knew what was going on and where. We had quantum-level switcheroo that nobody really wanted to touch, and I suspect it i...

Why is the Single Responsability Principle important?

The Single Responsability Principle is one of the five S.O.L.I.D. principles in which i base my everyday programming. It tells us how a method or class should have only one responsability. Not a long time ago i was designing a reporting service with my colleague Nuno for an application module we were redoing and we had a method that was responsible for being both the factory method of a popup view and showing it to the user. You can see where this is going now... I figured out it would not be a that bad violation of the principle, so we moved on with this design. The method was called something like "ShowPrintPopup" and it took an IReport as an argument. All this was fine, but then we got to a point where we needed to have a permissions system to say if the user was able to export the report to Excel, Word, PDF, etc... The problem was the print popup would need to know beforehand if it would allow the user to export the report or not, so that it could show it's UI a...

My simplest and most useful type

I have been doing some introspection on the way I write code to find ways that I need to improve. I consider this a task that one must do periodically so that we keep organized. There is a very, very simple problem that occurs in every application I know: How to return the results of an operation to the user? I've seen many implementations. Some return strings, some throw exceptions, some use out parameters, reuse the domain classes and have extra properties in there, etc. There is a myriad of ways of accomplishing this. This is the one I use. I don't like throwing exceptions. There are certainly cases where you have no choice, but I always avoid that. Throughout my architectures there is a single prevalent type that hasn't changed for years now, and I consider that a sign of stability. It is so simple, yet so useful everywhere. The name may shock you, take a look: Yes, this is it. Take a moment to compose yourself. Mind you, this is used everywhere , in every ...