3Desen




Dia: 20082012

Estudo revela o complexo ecossistema do setor de games

A ind\372stria de games \351 uma das mais pr\363speras do planeta, faturando entre US$ 60 bilh\365es e US$ 70 bilh\365es por ano, segundo consultorias como Gartner e DFC Intelligence. E a internet tamb\351m alimenta esse mercado: segundo a NewZoo Games Market Research, o Brasil \351 o quarto do mundo em gamers ativos na web, com 35 milh\365es (podendo chegar a 40 milh\365es este ano, diz a SuperData Research). Nesse \u201cjogo\u201d de mercado bilion\341rio, h\341 uma diversidade de players \u2014 desenvolvedores, est\372dios, distribuidoras, fabricantes de plataformas de hardware e, naturalmente, os consumidores. Pensando nisso, um grupo de professores e pesquisadores da Coppead/UFRJ criou um estudo para representar graficamente as rela\347\365es entre os diversos elementos da ind\372stria.

mobilidade e redes sociais: novos desafios

\u2014 O ecossistema dos games \351 parecido com um ecossistema biol\363gico, em que os v\341rios elementos se interconectam e apresentam diferentes \u201csimbioses\u201d \u2014 define Paula Chimenti, professora da Graduate School of Business da Coppead e uma das autoras do estudo. \u2014 N\343o \351 uma cadeia de neg\363cio tradicional, com empresa, fornecedor e cliente. Por exemplo, do ponto de vista da plataforma (digamos, um Xbox 360), h\341 v\341rios tipos de interessados al\351m dos jogadores, como anunciantes e desenvolvedores que querem programar para ela.

Partindo das tr\352s principais plataformas de consoles (Xbox, da Microsoft; PlayStation, da Sony; e Nintendo), o estudo tra\347a atrav\351s de um algoritmo (conjunto de regras aplicadas na solu\347\343o de uma proposi\347\343o) os desenvolvedores, distribuidores e consumidores mais ligados a cada uma delas e seus derivados.

\u2014 A diferen\347a do modelo econ\364mico que ilustramos \351 que ele d\341 grande destaque ao papel do consumo ao aproximar plataformas e editoras \u2014 explica o professor Luiz Felipe Hupsel Vaz, tamb\351m autor da pesquisa. \u2014 Por exemplo, o grande consumo de games da distribuidora/desenvolvedora Take Two na plataforma PlayStation 3 a torna mais pr\363xima dela no gr\341fico.

Os cruzamentos de consoles, editoras e consumidores determinam a \u201cfor\347a gravitacional\u201d que atrai um est\372dio ou distribuidora para um Xbox ou Nintendo DS. O estudo tamb\351m leva em considera\347\343o os chamados \u201csuperstars\u201d dos jogos \u2014 isto \351, games que se tornaram blockbusters, como \u201cCall of Duty: Modern Warfare 2\u201d, que vendeu 4,8 milh\365es de c\363pias para PS3.

\u2014 Esses jogos influem na movimenta\347\343o das rela\347\365es no ecossistema \u2014 diz Vaz. \u2014 Por exemplo, se um desenvolvedor pensa em programar para o Xbox 360, pode ter como alvo a desenvolvedora ZeniMax, dona do est\372dio que produz o game \u201cFallout 3\u201d, o qual vendeu 1,5 milh\343o de unidades no console da Microsoft. Segundo os pesquisadores, a ideia \351 que ele sirva de base para aplica\347\343o em outras ind\372strias, numa era em que as rela\347\365es econ\364micas mudam em alta velocidade.

A mobilidade, com smartphones, e redes sociais est\343o entre estas novas fronteiras que criam mais inter-rela\347\365es. Com menos intermedi\341rios, essas \341reas permitem aos programadores criar e lan\347ar t\355tulos diretamente na plataforma. Desenvolvedores brasileiros como a carioca Oktagon, que acaba de receber aporte de R$ 2 milh\365es do fundo NascenTI, bra\347o da Confrapar, apostam em modelos como o \u201cfreemium\u201d, em que o jogador acessa o game de gra\347a e, se gostar, passa a comprar itens virtuais ou troca dinheiro real por cr\351ditos para avan\347ar.

Mulheres preferem plataformas m\363veis

\u2014 A pessoa come\347a jogando gratuitamente e, quando passa a ter uma rela\347\343o mais \355ntima com o game, investe em itens para prosseguir mais r\341pido \u2014 diz Ronaldo Cruz, diretor executivo da Oktagon, que tem entre seus t\355tulos \u201cCuanatun\u201d. \u2014 E, diferentemente dos consoles, preferidos por homens, o p\372blico das plataformas m\363veis/sociais tem 30% de mulheres.


Governo apresentar\341 projeto de R$ 486 milh\365es para setor de software

Pacote prev\352 dobrar de faturamento do setor, para US$ 200 bilh\365es, al\351m de propor a cria\347\343o de 900 mil empregos em dez anos

S\303O PAULO - O governo federal apresentar\341 nesta segunda-feira (20) em S\343o Paulo um programa que destinar\341 R$ 486 milh\365es para o setor de software at\351 o ano de 2015. O jornal Folha de S. Paulo teve acesso ao documento final do projeto elaborado pelo MCTI (Minist\351rio da Ci\352ncia Tecnologia e Informa\347\343o) que apresenta a primeira pol\355tica espec\355fica para a ind\372stria nacional de software e servi\347os de TI.

O projeto prev\352 dobrar de faturamento do setor, para US$ 200 bilh\365es, al\351m de propor a cria\347\343o de 900 mil empregos em dez anos, e a capacita\347\343o de 50 mil profissionais para trabalhar no setor.

De acordo com a reportagem, o projeto tamb\351m prop\365e o aporte de capital nas empresas start-ups. A meta \351 investir em 150 empresas at\351 2015, sendo 25% estrangeiras, com investimento m\341ximo de R$ 200 mil em cada uma delas.

Ainda est\343o previstos no pacote do governo a cria\347\343o de uma certifica\347\343o para pequenas e m\351dias empresas para que participem de licita\347\365es de compras p\372blicas e a instala\347\343o de quatro centros de inova\347\343o no Pa\355s.

O jornal aponta ainda que um dos principais problemas da ind\372stria de software \351 concentrar esfor\347os na presta\347\343o de pequenos servi\347os de desenvolvimento de programas simples. Em 2001, do faturamento de US$ 14,5 bilh\365es do mercado brasileiro, 91% eram provenientes de servi\347os de menor valor agregado.


link

.NET
Melhorando o desempenho de aplicativos .NET \u2013 Parte 13
segunda-feira, 20/08/2012 \340s 11h08, por
Hovhannes Avoyan

No \372ltimo artigo, n\363s discutimos como otimizar as opera\347\365es string no .NET. Hoje vamos focar na otimiza\347\343o de arrays.

Os arrays oferecem funcionalidades b\341sicas para os tipos de agrupamento. Toda linguagem implementa sintaxe de array \340 sua maneira, embora as seguintes considera\347\365es se apliquem independentemente da linguagem:

Os arrays t\352m um tamanho est\341tico. Ele permanece fixo ap\363s a aloca\347\343o inicial. Se precisar estender o tamanho do array, voc\352 deve criar um novo array com o tamanho necess\341rio e, em seguida, copiar os elementos do array antigo;

Arrays d\343o suporte ao acesso indexado. Para acessar um item em um array, voc\352 pode usar seu \355ndice;

Arrays oferecem suporte o acesso enumerador. Voc\352 pode acessar os itens no array por enumera\347\343o, atrav\351s dos conte\372dos usando a constru\347\343o foreach (C #) ou For Each (Visual Basic NET);

A mem\363ria \351 cont\355gua. O CLR organiza arrays em espa\347os de mem\363ria pr\363ximos, que fornecem acesso r\341pido aos itens. Esta se\347\343o resume as diretrizes de desempenho para se considerar ao usar arrays:

Prefira arrays para cole\347\365es \u2013 a menos que voc\352 precise de funcionalidade; Use arrays fortemente tipadas; Use arrays de arrays ao inv\351s de arrays multidimensionais.

Prefira arrays para as cole\347\365es \u2013 a menos que precise de funcionalidade Arrays s\343o os mais r\341pidos de todas as cole\347\365es, a menos que voc\352 precise de uma funcionalidade em especial, como extens\343o din\342mica da cole\347\343o, voc\352 deve considerar o uso de arrays ao inv\351s de cole\347\365es. Arrays tamb\351m evitam a sobrecarga de boxing e unboxing.

Use arrays fortemente tipadas

Use arrays fortemente tipadas sempre que poss\355vel, ao inv\351s de usar arrays de objeto para armazenar os tipos. Isto evita a convers\343o de tipo ou o boxing, dependendo do tipo armazenado no array. Se declarar um array de objetos e, em seguida, proceder para adicionar um tipo de valor, como um inteiro ou um float, para o array, isso envolve a sobrecarga de boxing, como mostrado no seguinte exemplo de c\363digo:

Object[] array = new Object[10]

arr[0] = 2+3; //boxing occurs here
Para evitar a sobrecarga do boxing, declare um arry fortemente tipado, como mostrado a seguir:

int [] arrIn = new int [10];

arrIn[0] = 2+3;

Tipos de refer\352ncia de armazenamento, tais como strings ou classes personalizadas no array de objetos, envolve a sobrecarga do m\351todo. Portanto, use matrizes fortemente tipadas para armazenar os seus tipos de refer\352ncia, como mostrado no seguinte exemplo de c\363digo:

string[10]  arrStr = new string[10];

arrStr[0] =  new string(\u201cabc\u201d);

Use arrays de arrays ao inv\351s de arrays multidimensionais

Os elementos de um array de arrays podem ter dimens\365es e tamanhos diferentes. Use arrays de arrays ao inv\351s de arrays multidimensionais para se beneficiar a partir das otimiza\347\365es de desempenho MSIL.

O MSIL possui instru\347\365es espec\355ficas que visam arrays com uma \372nica dimens\343o baseado em zero (SZArrays) e o acesso a este tipo de array \351 otimizado. Em contraste, os arrays multidimensionais s\343o acessadas usando o mesmo c\363digo gen\351rico para todos os tipos, o que resulta em boxing e unboxing para arrays de tipos primitivos.

Vejamos um exemplo mostrando a declara\347\343o e o uso de arrays de arrays:

string[][] Address = new string[2][];  // A jagged array of strings

Address[0] = new string[1];

Address[1] = new string[2];

Address[0][0] = \u201cAddress [0,1]\u201c;

Address[1][0] = \u201cAddress [1,0]\u201c;

Address[1][1] = \u201cAddress [1,1]\u201c;

for (int i =0; i <=1; i++) {

      for (int j = 0; j < Address[i].Length; j ++)

            MessageBox.Show(Address[i][j]);

}

Voc\352 pode comparar a efici\352ncia de arrays de arrays vs multidimensionais estudando o c\363digo MSIL gerado em cada caso. Observe como o c\363digo a seguir, que usa um array multidimensional, resulta em uma chamada de fun\347\343o:

int [,] secondarr = new int[1, 2];

secondarr[0, 0] = 40;
O c\363digo anterior gera o MSIL seguinte. Observe a chamada de fun\347\343o:

IL_0029: ldc.i4.s   40

IL_002b: call instance void int32[0...,0...]::Set(int32,int32,int32)
O c\363digo a seguir mostra o MSIL gerado por um array de arrays. Observe a instru\347\343o MSIL Stelem que substitui o elemento do array em um determinado \355ndice com o valor int32 na pilha de avalia\347\343o:

int [][] intarr = new int[1][];

intarr[0] = new int[2];

intarr[0][0] = 10;
O c\363digo anterior gera o MSIL seguinte. Observe a utiliza\347\343o da instru\347\343o Stelem:

IL_001c:  ldc.i4.s   10

IL_001e:  stelem.i4

Considera\347\365es adicionais

Ao usar matrizes voc\352 tamb\351m deve considerar o seguinte:

Ordena\347\343o. Se voc\352 recuperar os dados de um banco de dados, veja se \351 poss\355vel classific\341-los previamente usando uma cl\341usula ORDER BY na sua consulta. Se precisa usar os resultados classificados do banco de dados para pesquisa adicional e classifica\347\343o do subconjunto de resultados, voc\352 pode exigir a classifica\347\343o dos arrays. Voc\352 sempre deve medir para descobrir qual abordagem vai funcionar melhor para o seu cen\341rio: ordena\347\343o, utilizando consultas SQL, ou ordena\347\343o utilizando arrays na camada de neg\363cios.

Evite retornar um array de uma propriedade. Em vez disso, considere o uso de propriedades de indexa\347\343o.

EmployeeList l = FillList();

for (int i = 0; i < l.Length; i++) {

   if (l.All[i] == x){\u2026}

}

No c\363digo anterior, cada vez que a propriedade All \351 usada, voc\352 pode criar e retornar um array. Se o c\363digo de chamada usa a propriedade em um loop, como mostrado no anterior, ser\341 criada um array em cada itera\347\343o do loop.

Al\351m disso, se voc\352 retornar um array de um m\351todo, o c\363digo resultante \351 um pouco n\343o intuitivo. Um exemplo de c\363digo est\341 a seguir. Em ambos os casos, documente os detalhes para sua API.

// calling code:

if (l.GetAll()[i]== x) {\u2026}

Se voc\352 tiver que retornar um array de uma parte de c\363digo, considere o envio de uma c\363pia para evitar problemas de sincroniza\347\343o entre os clientes.

No seguinte exemplo de c\363digo, cada chamada para a propriedade myObj cria uma c\363pia do array. Como resultado, uma c\363pia do array ser\341 criada a cada vez que o c\363digo DoSomething (obj.myObj [i]) for executado.

for (int i = 0; i < obj.myObj.Count; i++)

      DoSomething(obj.myObj[i]);
pp Em nosso pr\363ximo artigo veremos como otimizar o trabalhar com cole\347\365es.

***

O artigo original est\341 dispon\355vel em: http://blog.monitis.com/index.php/2012/05/15/improving-net-application-performance-part-13-arrays/ po Hovhannes Avoyan
\351 CEO do Monitis, um provedor de gerenciamento de sistemas e de monitoramento de software on-demand.
P\341gina do autor Email
Leia os \372ltimos artigos publicados por Hovhannes Avoyan

Melhorando o desempenho de aplicativos .NET \u2013 Parte 13

Melhorando desempenho de aplicativos .NET \u2013 Parte 12

Melhorando o desempenho de aplicativos .NET \u2013 Parte 11

Melhorando o desempenho de aplicativos .NET \u2013 Parte 10

Melhorando desempenho de aplicativos .NET \u2013 Parte 09


Inscri\347\365es em calend\341rios oficiais da Apple n\343o est\343o funcionando 6 coment\341rios postados
e Atualizado: 20/08/2012 \340s 19:21por Hugo Bessa 20/08/2012 \340s 19:21

Poucos sabem, mas a Apple h\341 alguns anos disponibiliza diversos calend\341rios com informa\347\365es \372teis, como datas de jogos de futebol americano ou feriados no Brasil. Eles podem ser adicionados ao Calend\341rio (Calendar) e s\343o atualizados automaticamente quando qualquer altera\347\343o \351 feita no lado do servidor.

Hoje, por\351m, o TUAW percebeu que os calend\341rios da Apple assinados n\343o est\343o mais sendo atualizados e n\343o podem mais ser baixados. Ao tentar faz\352-lo, o usu\341rio recebe um aviso de erro -1. Apesar de continuarem acess\355veis, usu\341rios n\343o podem mais assinar outros calend\341rios.

Os arquivos .ics continuam funcionando normalmente no aplicativo Calend\341rio, com excess\343o daqueles que utilizam informa\347\365es dos servidores da Apple. Resta saber se ela cancelar\341 o suporte aos \372teis calend\341rios ou se isso tudo n\343o passa de um problema interno/tempor\341rio.


Dia: 22/08/2012

GarageBand Tamb\351m usei o novo Mac para gravar m\372sicas no programa de m\372sica da Apple, o GarageBand. Levou menos de sete segundos para abrir o iPhoto e gerar imagens em miniatura de alta resolu\347\343o para 183 imagens de 12 megapixels. Em cinco segundos, ele importou 42 dessas imagens para o computador. Usando o Aperture, editei uma imagem com extens\343o RAW (n\343o processada) de 43,6 megabytes, com resultados imediatos. O laptop inicializou em poucos segundos.


link

dr dobbs - mike Rileyer Remote Mobile Debugging in Firefox 15
August 17, 2012
Post a Comment

Firefox 15, scheduled for release in the next few weeks, has a cool new remote debugging feature for mobile developers. By setting remote debugging to true in the "about:config" Firefox browser configuration for both the desktop and mobile (only available on the Android OS at this time) versions, developers can step into, walk, and modify JavaScript and DOM elements on the fly via the remote debugging window available in the desktop edition of Firefox.

By setting the remote debug values to true in the host and client Firefox browsers, the desktop version of Firefox connects to the exposed port number 6000 in the mobile version (you have to supply the IP address of your mobile phone).

Once the remote access permission session request initiated by the desktop version is granted by Firefox running on the mobile device, you're good to go. While it would be nice to see Firefox incorporate this debugging capability onboard the device (especially as Android tablets further proliferate the marketplace), this current solution provides an adequate stepping stone to get there.

And since the mobile edition of Firefox allows developers to extend the browser with add-ons, it would be awesome if Mozilla could port their incredibly helpful Firebug add-on to the mobile edition of Firefox. Even so, Mozilla just made the prospect of debugging web pages on Firefox Android a whole lot easier thanks to this new developer-friendly addition.

For more details about using the new Firefox 15 remote mobile debugging feature, check out this blog post by Firefox team member Kevin Dangoor.


Dr. Dobbs

link

This guest editorial is a rebuttal to my editorial last month, in which I argued that fine-grained parallelism will never become a standard part of programming skills. \u2013Ed.

When Herb Sutter told us in 2005 that our free lunch was gone, he helped spur a rash of predictions that parallelism would take over and serial programming heretics would soon be burned at the stake. Backed by the evidence of multicore processors becoming ubiquitous, the air of truth in urgent calls to action for parallelism led to me being quoted saying "Parallel or Perish." (It made for a very popular t-shirt.)

Seven years later, it is not unreasonable to ask whether parallel code will ever be embraced as Dr. Dobb's editor Andrew Binstock did last month. Since it seems like little has changed, we might even suggest that the earlier pronouncements were all a case of irrational exuberance. This suggestion then degenerates to the conclusion that parallelism on a universal scale is a failure and never meant to be.

Hogwash. Such seven-year-itch predictions have all the accuracy of the original sky-is-falling urgent calls to action for parallelism. It's an evolution, not a revolution. It's silently creeping over everything, and resistance is indeed futile. Relax! Let's enjoy the ride. The benefits of parallelism are everywhere, and the ability to harness it have become commonplace.

Multicore Was the Frontal Attack; the Flank Attack Was the Cloud. Battle Won. Parallel programming is using the multiple capabilities in a computing system in harmony to get a result faster or better than if we were limited to a single computing resource. You can also keep a multicore or many-core system busy with concurrency. The hardware does not care if the threads know each other or not; concurrency versus parallel program matters not.

Multicore processors are a localized parallel computing system. The vision of connecting the whole world via the Internet gave rise to "cloud" computing. What about "grid" computing? It lost the contest for which "hyped" word will dominate, and there isn't enough difference between "grid" and "cloud" for the world to need two names. They are both forms of parallel computing. Every cloud programmer contributes to providing parallel work for hungry cores, whether through their own parallel program or concurrency.

Hold On There, Please Define "Parallel Programmer"

Parallel programming orchestrates the actions of multiple processing devices to solve a problem collectively. Compared to having one "do-it-all" processing device to solve a whole problem, several challenges emerge: sharing, decomposition, and coordination \u2014 more specifically, data sharing, problem (algorithm/program) decomposition/refactoring, and coordination (synchronization) around the sharing of data and the program.

Parallel programming means dealing with communication and computation. In recalling the "good old days" of sequential programming, our memories only recall worrying about computation. It seems that parallel programming requires communication be part of the job of programming now, and that additional work must mean it is harder.

Cloud programmers worry about communication a lot, but it is often so obvious we do not talk about it. Imagine the difference in the following pseudo-code queries to see what Apple II computers are on eBay this week:

Version 1 (c. 1996)

Display_EBay_ForSale( "Apple II" ) =>
  {
    all_items = download( EBay );
    my_items = match( \u201cApple II\u201d, all_items );
    display my_items;
  }
Version 2 (c. 2004)

Display_EBay_ForSale( "Apple II" ) => 
  { 
    my_items = match_on_server("Apple II", EBay ); 
    display my_items;
  }

Version 1 downloads all listings and then scans them locally; Version 2 asks the server to do the scan and only return matches. Version 2 therefore both reduces communication and offloads the work to the more powerful (and almost certainly multicore processor based systems) in the "cloud." Parallel computing is here twice: once in using the cloud, and again within the cloud in a highly parallel eBay system full of clever parallel programming ready to do the parallel computing for our two line program.

Is this client side parallelism or server side? The server operates in parallel, and the client benefits from that. It was the client programmer who chose Version 2 over Version 1. Therefore, the client programmer is a parallel programmer. Such programmers are better when they understand parallelism enough to make good choices to produce effective programs.

Is That Really Parallel Programming? It is parallel programming \u2014 because parallel programming is just about using multiple compute devices intelligently. "Intelligently" means putting the right work at the right place and not doing anything overwhelmingly stupid with the data (such as copying the entire Library of Congress to your desktop in order to locate and print out a single sentence).

In this sense, we all need to be parallel programmers. Here is why writing that makes you a parallel programmer and makes that parallel code: Parallel programming means thinking different. "Think Parallel." The most important topics are program decomposition and data location/sharing decisions (often simply lumped together as "communication"). As soon as you decide "Display_EBay_ForSale" needs to do the query in the cloud and it needs to move only the answer to the local machine, you have made critical parallel programming decisions. Call yourself a parallel programmer with all the rights and privileges that accompany this honor.

Multicore Parallelism Accessed in Many Ways All this talk of clouds was not meant to discount multicore parallelism. It does suggest that we need to look for more than OpenMP directives or Threading Building Block (TBB) calls to detect parallelism in our code. We need to look for decisions being made by programmers on code and data placement in a parallel world. This includes scaling up versus scaling out decisions, too.

We all become parallel programmers because, if we do not, we have a blind spot to one of the most important aspects of modern computing. We should already all be data structure programmers, and numerical programmers, and database programmers, GUI programmers, and Internet programmers. While we are likely to be experts in a narrower field, very few programmers should be able to say, "I know nothing at all about GUIs or the Internet." Would you hire a programmer today who knew nothing about the Internet? A decade ago, that was not a universal expectation, and a decade before that, the Internet was unimportant to almost all programming jobs. Likewise, text-only displays are hardly the expectation of most programmers today. Parallel programming will have this status within the decade, and already does for many developers today.

I have a love for deep, detailed parallel programming, especially the very precise wring-all-the-performance world of HPC (high-performance computing, also known as supercomputing). That makes me a pretty serious parallel programmer. Most programmers will never devote as much of their life to parallel programming. I know programmers who enjoy graphics at least as much as I enjoy parallel programming. Others feel the same about database programming, and others about writing compilers. Each is a specialty. All of us need to know enough to get what we need of these specialties.

College Students: Get Your Money's Worth These days, if you study programming and never do a parallel program during your time in college, you need to demand you money back. Seriously.

Core concepts need to be part of every programming curriculum. Not to create deep HPC programmers out of all of us, but definitely to avoid people writing Version 1 of Display_EBay_ForSale and thinking they did their programming well.

All of us need to know this. And every program needs to be written by someone who understands these aspects, even if the decision is that a sequential program is just fine. Every once in a while, a text-based program will do. It's just much less common than twenty years ago. Similarly, parallel programs will gradually take over, but perhaps the same way GUIs did\u2026sometimes as a wrapper and other times through a rethinking and rewrite.

Scale up or scale out, it is better when we know enough about the key concepts of parallel programming to make a decision. Relax and enjoy the ride.

Yes, I agree with Andrew's editorial\u2026fine-grained parallel programming is a specialty, most programmers should have enough parallel/concurrency knowledge to program coarse-grained parallelism well. No one escapes entirely, but most will escape being fine-grained parallelism code jocks.

James Reinders is Intel's leading spokesperson on tools for parallelism, and author of the O'Reilly Nutshell book on Intel Threading Building Blocks.


link

.NET

inShare

Share on reddit
Permalink
Saying No To Properties
By Allen Holub, August 21, 2012

6 Comments

Properties are rarely necessary and, in many cases, they make your classes hard to extend and difficult to debug. And they make code much larger and more complex than it needs to be. I was interested to find the following statement in the comments section of last month's article on the enum pattern in C#: "I was rather stunned by the author's casual mention (in parenthesis) that one of the things he apparently dislikes most about C# is Properties \u2014 that's one of its strongest and most important features\u2026" My reaction is that I'm stunned that he's stunned. Properties (and their cousins: explicit accessor/mutator \u2014 getter/setter \u2014 methods) have been discussed in great depth over the past 30 years. It's not as if mine were a new or out-of-the-mainstream point of view. You can choose to disagree, of course, but you shouldn't be stunned.

Let's look in depth at the reasons for my off-the-cuff remark.

Disclaimers

I know from past flame wars that the point of view in this article will be controversial to some, so I want to start with a few disclaimers.

I'm mostly platform-agnostic when it comes to software construction. Use what works for you. We're talking about properties, though, and properties are solidly in the middle of the Microsoft world. Microsoft makes fine products. Nonetheless, I've noticed that many programmers in the Microsoft ecosystem are somewhat insular: They accept the Microsoft party line when it comes to architecture without much curiosity about the alternatives, and often assume that Microsoft "best practice" is universal across the board. It isn't.

I am in no way arguing in this article that you should not use properties to implement code for the various Microsoft frameworks that require them. Properties are a fundamental part of Microsoft's thinking, and you can't possibly eliminate them altogether and still program for .NET in any meaningful way.

That does not mean, however, that you should use properties indiscriminately throughout your code. The best programmers understand the pros and cons of all of the programming idioms that they use, and make intelligent trade-offs by weighing them. You simply can't work competently unless you understand both sides of an issue. Using properties (or any design pattern) blindly can lead to no good outcome. There are no absolutes in good design.

The point of this article, then, is to discuss the cons of properties, so that you can make smart choices about when (and when not) to use them. You already know the pros, so I'm not going to spend time discussing them here.

No Surprises
So, what's wrong with properties?

Let's start with the simplest issue. One of the most important basic principles of good programming is: There should be no surprises. Code should work intuitively, and you should never set up a situation where you can be bitten by side effects. It's too easy to violate that principle if you use properties. Consider the following code.

public class MyClass
{
    public int MyProp { get{ return readValueFromConfigurationFile("myProp"); }
                        set{ modifyConfiguration("myProp", value); } 
                      }

This code looks reasonable on the surface. However, the readValueFromConfigurationFile("myProp"); call throws an exception both when it can't read the value and when it can't parse the value that it reads. The modifyConfiguration(...) method has similar issues. The problem lies in this code:

MyClass x;
//...
int value = x.MyProp;

I am shocked that these harmless looking assignments might bring down my server via an uncaught exception. It simply doesn't occur to most programmers that they need to surround assignments with try/catch statements. (More to the point, I've seen code exactly like this many times, and I've never seen a surrounding try/catch.)

There are many variations on this theme. A concurrency bug in a getter or setter could put us into a totally unexpected deadlock situation if it has to use locking, for example (and a property that looks like an atomic assignment should certainly use locking to guarantee atomicity in a multithreaded application). I've also seen properties that make database calls, and the resulting inefficiency is another surprise.

This is dangerous stuff. A statement as simple as x.prop = 0; should not bring a server to its knees. Throwing an exception or making a database call in a property is just as bad as overloading a + operator to do subtraction. Noting that assignment to a property can throw an exception in the "class contract" (which in C# is just a documentation comment with no compiler-level enforcement) is not good enough, just as noting that + actually does a - in the class contract is insufficient. A contract of that sort is fundamentally flawed because it violates the rules of common sense.

I also don't buy the argument that "you shouldn't do that." If the point of a property is to hide implementation in such a way that it can be changed without clients noticing, then I should be able to make any change without introducing surprising and dangerous behavior. The language just shouldn't permit those sorts of changes. That is, the arbiter of the class contract should be the compiler. If the compiler cannot make at least a few fundamental guarantees, then the language is flawed. Modifying a normal method might be dangerous, but at least it's not surprising.

I might feel a little better about this situation if C# supported a Java-style "checked exception," which guarantees a compiler error if you don't handle an exception. Checked exceptions would, at least, give us a real contract that was enforced by the compiler. However, even a checked exception wouldn't address the it's-not-intuitive issue.

I'm really making the same argument, here, that I made last month in discussiong C#'s flawed approach to enums. It simply shouldn't be possible to pass a method that takes an enum argument some value that doesn't correspond to any enum element. The fact that you can do so in C# is a flaw in the language; the whole point of a constrained type, after all, is that it be constrained.

OO Issues

Now let's move on to the object-oriented design issues. It's a fundamental OO principle that an object should be a black box. You send it messages and it does work for you. You should not know how it does the work, however. That is, an object is defined by the work it does, and the way that it does the work should be hidden. That's what is meant by encapsulation.

The main problem with properties (or explicit get/set functions) is that they provide too much access to the underlying implementation of the object. They don't have to, of course, but most applications of properties are not much different from public fields. In fact, I often see the idiom

public int x {get;set;}

Many books even recommend that you use that idiom for every one of your fields! However, that's literally no different than

public int x;

So why is the violation of encapsulation by providing direct or indirect access to fields a problem? The first issue is maintenance. You should be able to modify a class's implementation \u2014 completely scrap it, in fact \u2014 and as long as the interface (the method signatures) does not change, the clients of the class (the objects that send messages to instances of your class) should not know that a change has happened. Over use of properties makes that level of encapsulation impossible, but when you don't have it, the consequences of even a simple change can be significant.

If you're working in an Agile development environment, code that's not built to be this robust simply can't stand up to the rigors of the development process, which mandates constant small changes \u2014 the changes end up requiring so much work that you can't really be Agile.

Let's look at a concrete, though simplistic (I use the word deliberately) example: A Money-class implementation:

class Money
{
    public float Value { get; set;}
    //...
}

What happens when we decide that Value should really be a decimal, not a float. The notion of a property providing a way to make changes transparently doesn't really work here because the code that uses the Money objects will, most likely, not be able to accept that particular change from float to decimal. That is, a statement like:

Money m; 
//...
 float value = m.Value;
won't compile if I change the float to a decimal. It's unreasonable to expect the code to have been written in such a way as to protect itself from that sort of change. For example, you won't expect the client code to look like this:
Money m; 
//... 
decimal value = (decimal) m.Value;

Put in design terms. The class "contract" cannot stand up to obvious modification. Whether or not you follow the contract is immaterial. The contract itself is flawed.

1 2 3 Next

.NET

inShare

Share on reddit
Permalink
Saying No To Properties
By Allen Holub, August 21, 2012

6 Comments

Properties are rarely necessary and, in many cases, they make your classes hard to extend and difficult to debug. And they make code much larger and more complex than it needs to be. Unfortunately, this is the case with virtually every contract that relies on a property. The class contract becomes unenforceable. The only way to fix the problem is to completely hide the type of the Value object, but there's no way to do that if we expose the object to the outside world. Value must be be completely encapsulated inside the object. (It should be private with no public accessor or mutator.)

To drive the point home, having a Value without a currency isn't of much use. If you're thinking in terms of properties, however, it's tempting to do something like the following to add the notion of currency:

class Money
{
    public decimal      Value    { get; set;}
    public CurrencyCode Currency { get; private set;}
    //...
}
The amount of work this simple change requires is simply unacceptable. For example, your original code might calculate a simple sum: total.Value += item.Value; Once we introduce the Currency property, however, we need to change that simple statement to something like the following:
total.Value += item.Value * 
            CurrencyCoverter.getExchangeRate(
                            total.Currency, lineItem.cost.Currency);
The new code is ugly, but more significantly, we have to make a similar change everywhere we add together two units of Money. That could add up to many hundreds, or even thousands, of changes scattered throughout the code, and we'll almost certainly miss a few, thereby introducing many new bugs. Automatic refactoring won't do this work for us.

You could argue that you can do the currency conversion in the Value setter, which is definitely a move in the right direction. I'd wager that a better approach is to give up on the properties entirely and completely hide the way that the value is represented from the outside world.

Here's what I'd do. Let's first rewrite the simplistic example to hide implementation:

class Money
{   private readonly float value;
 
    public Money ( float value )
    {   this.value = value;
    }
    public Money plus( Money operand )
    {   return new Money(value + operand.value);
    }
}

I can now update the total like this:

Money total;
Money item;
//...
total = total.plus( item );

Of course, I could use operator overloading to make it look like this:

total += item;

but I'll keep the example simple.

The first thing to notice is that full encapsulation has made the client code simpler (and shorter), and that alone is a good reason to use this approach. You will (hopefully) use Money more often than you define it, so encapsulation can result in considerable reduction in code size, along with the concomitant reduction in development time and debugging cost. It takes a bit longer to write the class, but it takes a lot less time to write the code that uses the class.

Let's see how this approach holds up to change. What if I want to change the internal representation of value to decimal? Here's the new class:

class Money
{   private readonly decimal value;
 
    public Money ( decimal value )
    {   this.value = value;
    }
 
    // For backwards compatibility
    public Money ( float value ) : this( (decimal)value )
 
    public Money plus( Money operand )
    {   return new Money(value + operand.value);
    }
}

Note that the code to compute the sum hasn't changed at all. It still looks like this: total = total.plus( item ); That point is the essential one. I can change the implementation without changing any of the code that uses the original implementation.

To drive in my point, let's add the notion of currency:

class Money
{
    private readonly decimal      value;
    private readonly CurrencyCode currency;
 
    public Money ( decimal value, CurrencyCode currency = CurrencyCode.USD )
    {   this.value = value;
        this.currency = currency;
    }
 
    //...
 
    public Money plus( Money operand )
    {
        decimal newValue == value +
            (operand.value *
                CurrencyCoverter.getExchangeRate(currency, operand.currency));
 
        return new Money(newValue, currency );
    }
}

The code that does the sum has still not changed: total = total.plus( item );

I hope you're getting the idea. By fully encapsulating the implementation of Money \u2014 eliminating the properties entirely \u2014 I end up with an implementation that I can change radically without changing any of the code that uses the Money class.

This sort of flexibility is much more difficult to achieve if you use properties.

What about testability? The fact that the client code isn't changing gives us a test advantage. In general, it's a bad idea to change both your test and the class that you're testing at the same time. If you do, you're never sure whether a bug is in the test or in the class. In a regression-test environment, you don't really want to change your test code at all. (That's not to say that a test doesn't have a lifetime. In an Agile world, it's possible for a class to have to change enough that the old tests simply aren't useful any more, in which case they should be discarded.) With properties, though, you'll certainly have to rewrite your tests every time a property changes type (or you add or remove one).

Properties also add unnecessary coupling relationships between classes, which also hurts testability. For example, if you use a property, you need to test not only the object you're interested in, but also all the objects whose properties are accessed and the interactions between the entire system of interlocking objects. That makes it very difficult to write a unit test \u2014 or more accurately, your smallest "unit" becomes a system of interrelated classes rather than a single class.

Previous 1 2 3 Next

Saying No To Properties By Allen Holub, August 21, 2012

6 Comments

Properties are rarely necessary and, in many cases, they make your classes hard to extend and difficult to debug. And they make code much larger and more complex than it needs to be. The final test-related issue is something called The Law of Demeter, "Talk only to your friends." This means that your code should use only those objects that it can see directly: local variables, fields, and method arguments. Code like this:

dog.getBody().getTail().wag()

is considered bad form because it requires dependencies on too many interfaces to get work done. Translating that code into properties:

dog.tail.body.wag();

just obscures the problem.

In the test-driven-development (TDD) world, this sort of chain is called a train wreck. A program that follows The Law of Demeter would restate the chain like this:

dog.expressHappiness();

You'd leave it up to the dog to figure out how to tell you it's happy.

This sort of structure is particularly important in TDD because it lets you bring your mocking architecture under control. If you follow The Law of Demeter, the object that you're testing is always three layered:

The outer layer (objects that you are passed).
The object under test.
The inner layer (objects that you create).
When you build the mocks, you may need to mock classes in layers 1 and 3, but that's it. In the train-wreck example, you'd have to mock every car in the train, which can be a very difficult and time-consuming process.

Mock Roles, Not Objects [PDF] is a great formal paper on this subject. In fact, I'd strongly recommend spending some time perusing http://static.mockobjects.com/. There's a lot of good information there.

Getting Rid of Getters/Setters

So, how to you eliminate the get/sets? The main key is rethinking the approach to objects. An object should be defined by what it does, not by what it contains. In fact, you shouldn't know what the object contains.

The first step, then, is to stop thinking of an object as a sort of fancy data structure that contains fields and methods that manipulate those fields. Instead, think of an object as something that does work. Money isn't a value and a currency. Rather, it's an abstract object that supports certain operations, such as addition. A dog's job is to express happiness. The way that it does it (by wagging its tail) is unimportant.

These work-centric objects will, of course, have to contain fields in order to do their work, but the outer world shouldn't care about that. The objects that have the information do the work, and if they can't do the work, they delegate to another object by calling one if its methods.

Some information has to pass between objects, of course, but a push (that is, an argument to the target object's method) is usually considered better than a pull (a get method on another object).

This approach is at the core of OO design and is too big a subject for a single article, but I have illustrated the basic concept. When you follow good design principles, the get/set methods (or the equivalent properties) tend to wither away. They don't creep into the code to begin with because getting something is rarely a bit of work that's worth modeling. Instead, you simply ask the object that has the information to do the work for you. Ken Arnold put it as "ask for help, not for information." The formal term for this sort of organization id delegation.

Conclusion

So, to put things succinctly. Properties are rarely necessary, and in the worst case, they make your classes hard to extend and hard to debug. They make client code much larger and more complex than it needs to be. That's not to say that there's never a valid application for properties, but they should be used judiciously, knowing what the downside is. The way that you go about eliminating the use of properties is by following well-established design practices, looking at your objects as black boxes that do work, not as data structures. I hope that's not stunning.

Allen Holub is a speaker, lecturer, and writer on software development. His recent books have discussed Java, multithreading, and the use of patterns. He is a frequent contributor to Dr. Dobb's.

More Articles by Al flen Holub

Fixing the enum in C#

Testing OO Systems, Part 1

Testing OO Systems, Part 2

Type-Safe File-Based Configuration


link

Desenvolvimento + iOS + Mobile

Desenvolver um aplicativo de apresenta\347\343o de slides do iOS para iPad ter\347a-feira, 24/07/2012 \340s 10h07, por br Developerworks Brasil

N\343o \351 mist\351rio o motivo pelo qual escrever aplicativos para um dispositivo iOS, como iPad ou iPhone, \351 uma atividade muito popular: os dispositivos s\343o incr\355veis e f\341ceis de usar. Com milh\365es de usu\341rios, os dispositivos s\343o muito lucrativos para desenvolvimento de aplicativos. As pessoas gostam de ver suas fotos no belo visor dos iPads e iPhones.

Neste artigo, aprenda a desenvolver um aplicativo de apresenta\347\343o de slides de fotos do iOS a partir do zero. Voc\352 colocar\341 parte do c\363digo XML e das fotos no servidor, desenvolver\341 o aplicativo iOS, adicionar\341 uma visualiza\347\343o de imagem, obter\341 XML e far\341 a anima\347\343o da apresenta\347\343o de slides.

Desenvolvendo o Backend

O backend do aplicativo de apresenta\347\343o de slides de exemplo \351, na verdade, apenas um arquivo XML que pode ser colocado no seu servidor. Veja abaixo o XML de exemplo com algumas imagens de amostra:

<photos&>
<photo url="http://localhost/photos/CRW_0675.jpg" /> 
<photo url="http://localhost/photos/CRW_1488.jpg" /> 
<photo url="http://localhost/photos/CRW_3273.jpg" /> 
<photo url="http://localhost/photos/CRW_3296.jpg" /> 
<photo url="http://localhost/photos/CRW_3303.jpg" /> 
<photo url="http://localhost/photos/CRW_3359.jpg" /> 
<photo url="http://localhost/photos/CRW_3445.jpg" /> 
<photo url="http://localhost/photos/CRW_3752.jpg" /> 
<photo url="http://localhost/photos/CRW_3754.jpg" /> 
<photo url="http://localhost/photos/CRW_4525.jpg" /> 
<photo url="http://localhost/photos/CRW_4547.jpg" /> 
<photo url="http://localhost/photos/CRW_4700.jpg" /> 
<photo url="http://localhost/photos/CRW_4860.jpg" /> 
</photos> 

O XML \351 muito simples. A tag cont\351m diversas tags . Cada uma tem a URL da imagem que voc\352 deseja exibir. A URL precisa estar totalmente qualificada e ser absoluta; o aplicativo cliente carregar a URL diretamente, e n\343o atrav\351s de algum tipo de navegador que manipule as URLs relativas.

Para concluir o backend, modifique o XML para incluir refer\352ncias \340s suas fotos e efetue o upload desse XML para um local conhecido no seu servidor. Se tudo sair conforme o planejado, voc\352 poder\341 navegar para o XML usando o Safari (ou qualquer navegador escolhido) e ver algo como o que \351 mostrado abaixo.

A figura mostrou o XML da lista acima formatado como texto. O resultado ser\341 diferente de navegador para navegador, uma vez que esse \351 apenas XML simples (e n\343o h\341 padr\343o entre navegadores).

Para testar se as URLs est\343o corretas:

Deve-se visualizar algo similar a:

Uma foto, localizada no servidor, \351 referida por uma das URLs no XML. Se voc\352 n\343o visualizar o XML, ou n\343o visualizar as fotos, \351 preciso verificar a configura\347\343o do servidor da web e as URLs. Se voc\352 n\343o conseguir ver uma foto no navegador, o novo aplicativo do iOS n\343o consegue v\352-la tamb\351m.

Desenvolvendo o aplicativo de apresenta\347\343o de slides cliente

Depois de o servidor ser configurado e as fotos serem transferidas por upload, \351 poss\355vel come\347ar a desenvolver o aplicativo iOS. A primeira etapa \351 instalar as Apple Developer Tools (consulte \u201cRecursos\u201d para obter um link). Se voc\352:

Depois de instalar as ferramentas do desenvolvedor, execute o ambiente XCode, que \351 o IDE da Apple para desenvolvimento de iOS e Mac OS X. A partir do ambiente XCode, selecione a op\347\343o de menu para New Project. Deve ser poss\355vel ver a primeira p\341gina do assistente do aplicativo que ser\341 usado para desenvolver aplicativos do iOS ou Mac OS X, como abaixo:

\311 poss\355vel escolher entre v\341rios modelos de aplicativos diferentes. Para este exemplo, selecione View-based Application e clique em Next . Deve ser poss\355vel ver a p\341gina final do assistente, como abaixo:

Na segunda p\341gina do assistente, atribua um nome ao aplicativo e selecione a fam\355lia de dispositivos padr\343o (iPad ou iPhone). O Product Name do aplicativo de exemplo \351 slideshow. O valor no campo Company Identifier indica que o aplicativo est\341 no namespace com.jherrington . (\311 claro, \351 poss\355vel escolher qualquer nome e identificador da empresa que voc\352 desejar.) Escolha iPad para a Device Family e clique em Next.

O projeto \351 criado. Neste ponto, \351 sempre melhor selecionar o bot\343o Play grande no canto superior esquerdo da interface para executar o aplicativo pela primeira vez. Esta etapa compila tudo e ativa o emulador do iPad.

Adicionando a visualiza\347\343o da imagem

A pr\363xima etapa \351 adicionar a visualiza\347\343o da imagem para a exibi\347\343o das imagens. A estrutura do iOS vem com um conjunto avan\347ado de controles integrados que podem ser usados para desenvolver o aplicativo. Para o exemplo, voc\352 usar\341 o controle UIImageView. Com UIImageView, \351 poss\355vel exibir as imagens que s\343o compiladas no aplicativo, armazenadas localmente no dispositivo, ou, como no exemplo, transferidas por download de um website.

Para adicionar UIImageView, abra o arquivo slideshowControllerView.XIB, que \351 o arquivo de defini\347\343o de interface com o usu\341rio para slideshowControllerView. Com o XIB aberto, acesse a paleta de objeto e selecione Image View, como abaixo:

Com Image View selecionado, arraste e solte-o em slideshowControllerView. Normalmente, o IDE escala o controle de maneira autom\341tica para caber no espa\347o dispon\355vel. Se ele n\343o couber, simplesmente arraste o controle para ajustar seu tamanho at\351 que preencha toda a \341rea de exibi\347\343o.

r Depois de o controle estar na visualiza\347\343o, defina alguns dos par\342metros para obter um visual e uma experi\352ncia ideais para o aplicativo. A figura abaixo mostra as configura\347\365es na tela de atributos para o controle Image View.

As duas modifica\347\365es necess\341rias s\343o para Mode e para Background. Defina Mode para Aspect Fit de maneira que a imagem seja escalada, mas ainda preserve o formato original. Se Aspect Fit n\343o for usado, suas imagens ir\343o ser estendidas para corresponderem \340 \341rea de exibi\347\343o da visualiza\347\343o de imagem\u2014 e elas podem acabar tendo uma apar\352ncia muito estranha.

Como \351 poss\355vel que a imagem nem sempre se ajuste \340 \341rea dispon\355vel, tamb\351m \351 preciso definir o atributo Background para Dark Text Color ou usar um seletor de cores para escolher um preto profundo. Por padr\343o, esse valor \351 branco. A maioria das fotos n\343o tem uma boa apar\352ncia quando emoldurada por um branco brilhante.

Salve o arquivo XIB e passe para o arquivo SlideshowViewController.h. Fa\347a a pequena modifica\347\343o na lista a seguir:

#import 

@interface slideshowViewController : UIViewController {
    IBOutlet UIImageView *imgView;
}

@end

\311 preciso adicionar Outlet ao slideshowViewController que permite ao controle definido no XIB conectar-se \340 classe do controlador de visualiza\347\343o.

Depois de a sa\355da ser adicionada, retorne para o arquivo XIB, selecione UIImageView e use o inspetor de conex\365es para vincular o objeto UIImageView \340 vari\341vel imgView na classe slideshowViewController .

Depois de a conex\343o ser feita, fa\347a as modifica\347\365es do c\363digo \340 classe do controlador de visualiza\347\343o da apresenta\347\343o de slides em si para carregar uma imagem. A pr\363xima lista mostra a primeira vers\343o completa da classe.

#import "slideshowViewController.h"

@implementation slideshowViewController

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
        [super viewDidLoad];

    NSURL *imageURL = [NSURL URLWithString:@"http://localhost/photos/CRW_0675.jpg"];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    [imgView setImage:image];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:
                                       (UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

@end

O trabalho mais duro na classe slideshowViewController \351 feito no m\351todo viewDidLoad , que agora:

Neste ponto, voc\352 deve executar o aplicativo para testar se uma imagem aparece. Deve-se visualizar algo similar \340 figura abaixo, que mostra uma imagem exibida no emulador do iPad.

Se voc\352 n\343o visualizar a imagem, o problema provavelmente \351 com a chamada do m\351todo setImage para imgView. Verifique se o objeto UIImageView est\341 adequadamente conectado \340 vari\341vel imgView . Se o aplicativo falhar antes disso, \351 poss\355vel que voc\352 n\343o tenha a URL correta ou que algo n\343o esteja correto no servidor.

Analisando o XML

Agora que voc\352 tem uma maneira de exibir as imagens em um iPad, a pr\363xima etapa \351 carregar o XML para obter uma lista de todas as imagens a exibir. A estrutura do iOS tem um analisador de XML integrado, ent\343o \351 necess\341rio simplesmente criar o objeto analisador e receber retornos de chamada para as v\341rias tags.

Estenda a classe em si com a interface NSXMLParserDelegate , que diz \340 estrutura do iOS que essa classe \351 capaz de receber retornos de chamada do analisador de XML. Tamb\351m pode ser necess\341rio adicionar um array chamado photos que det\351m a lista de URLs extra\355das do XML. A listagem abaixo mostra as atualiza\347\365es:

 
#import 

@interface slideshowViewController : UIViewController {
    IBOutlet UIImageView *imgView;
    NSMutableArray *photos;
}

@end

Conforme voc\352 escreve mais aplicativos do iOS, descobrir\341 que usa cada vez mais delegados para conectar-se \340s v\341rias APIs. H\341 retornos de chamadas de dados para tabelas, elementos da UI, retornos de chamada de GPS, etc. \311 poss\355vel inclusive criar suas pr\363prias interfaces personalizadas para as suas pr\363prias bibliotecas.

Para usar o analisador de XML, estenda a classe do controlador de visualiza\347\343o, como a seguir:

 
- (void)viewDidLoad {
        [super viewDidLoad];

    photos = [[NSMutableArray alloc] init];

    NSXMLParser *photoParser = [[[NSXMLParser alloc] 
       initWithContentsOfURL:
       [NSURL URLWithString:@"http://localhost/photos/index.xml"]] autorelease];
    [photoParser setDelegate:self];
    [photoParser parse];

    NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    [imgView setImage:image];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
   namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
   attributes:(NSDictionary *)attributeDict { 
    if ( [elementName isEqualToString:@"photo"]) {
        [photos addObject:[attributeDict objectForKey:@"url"]];
    }
}

A classe agora cria um analisador no m\351todo viewDidLoad e faz com que ele solicite e analise o XML do servidor. Tamb\351m define o delegado para o analisador de volta para ele mesmo, de modo que receba retornos de chamada.

No exemplo, voc\352 deseja receber o retorno de chamada didStartElement que \351 acionado sempre que uma tag encontrada. A fun\347\343o didStartElement ent\343o olha para o nome da tag para ver se \351 uma tag de foto. Se for, didStartElement adiciona o valor do atributo url ao array de fotos.

Depois de o array de fotos ter sido conclu\355do, o m\351todo viewDidLoad continua e define a imagem para a primeira imagem no array.

Execute o aplicativo para testar seu progresso. Deve ser poss\355vel ver a primeira imagem especificada no XML aparecer no emulador. Se voc\352 n\343o visualizar a primeira imagem, pode haver um problema com o XML no servidor. Defina um ponto de interrup\347\343o no m\351todo didStartElement para ver se ele est\341 sendo chamado. Se n\343o estiver, voc\352 n\343o est\341 recebendo nenhum XML v\341lido de volta do servidor.

Animando a apresenta\347\343o de slides

A etapa final \351 usar o array de fotos para animar uma apresenta\347\343o de slides. Dois itens ser\343o necess\341rios:

Um timer;

Uma vari\341vel para conter o seu local atual na apresenta\347\343o de slides. Adicione ambos os itens \340 defini\347\343o de classe, como na pr\363xima lista.

 
#import 

@interface slideshowViewController : UIViewController {
    IBOutlet UIImageView *imgView;
    NSMutableArray *photos;
    NSTimer *timer;
    int currentImage;
}

@end

O timer \351 um objeto que acionar\341 eventos a um intervalo especificado. O currentImage \351 simplesmente um \355ndice para o array de fotos que ser\341 usado para iterar atrav\351s de todas as imagens.

A lista abaixo mostra a vers\343o final do c\363digo de aplicativo da apresenta\347\343o de slides.

 
#import "slideshowViewController.h"

@implementation slideshowViewController

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
        [super viewDidLoad];

    photos = [[NSMutableArray alloc] init];

    NSXMLParser *photoParser = [[[NSXMLParser alloc] 
      initWithContentsOfURL:[NSURL URLWithString:
      @"http://localhost/photos/index.xml"]] autorelease];
    [photoParser setDelegate:self];
    [photoParser parse];
    
    currentImage = 0;

    NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    [imgView setImage:[UIImage imageWithData:imageData]];

    timer = [NSTimer scheduledTimerWithTimeInterval: 5.0
                                             target: self
                                           selector: @selector(handleTimer:)
                                           userInfo: nil
                                            repeats: YES];
}

- (void) handleTimer: (NSTimer *) timer {
    currentImage++;
    if ( currentImage >= photos.count )
        currentImage = 0;

    NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:currentImage]];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    [imgView setImage:[UIImage imageWithData:imageData]];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
   namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
   attributes:(NSDictionary *)attributeDict { 
    if ( [elementName isEqualToString:@"photo"]) {
        [photos addObject:[attributeDict objectForKey:@"url"]];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:
                                       (UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

@end

Os dois novos elementos na lista acima s\343o a cria\347\343o do timer no m\351todo viewDidLoad e a adi\347\343o do m\351todo handleTimer , que \351 chamado quando o timer \351 acionado. O m\351todo handleTimer simplesmente incrementa currentImage, ent\343o rola o \355ndice se atingir o fim do array. Tamb\351m usa a l\363gica de an\341lise de imagem padr\343o para obter a imagem no dado \355ndice e exibi-la.

Os timers t\352m dois modos: podem ser acionados uma vez ou ser acionados continuamente. No m\351todo viewDidLoad , o exemplo especifica YES para repeti\347\365es, de modo que o m\351todo handleTimer \351 chamado repetidas vezes durante o ciclo de vida do aplicativo.

Conclus\343o

Neste artigo, voc\352 criou um aplicativo b\341sico do iOS. Agora \351 poss\355vel levar o aplicativo para v\341rias dire\347\365es diferentes. A estrutura iOS CoreGraphics fornece um conjunto avan\347ado de transi\347\365es que podem ser usadas para animar a troca de imagens. \311 poss\355vel usar PHP no backend para gerar o XML dinamicamente. Ou \351 poss\355vel inclusive usar a API CoreAudio para colocar m\372sica junto com toda a apresenta\347\343o de slides.

Recursos
Aprender

Portal do Desenvolvedor Apple: obtenha o IDE, forne\347a seus dispositivos de teste e fa\347a o upload de aplicativos conclu\355dos para o armazenamento.

iOS Developer Library: aprenda os fundamentos do desenvolvimento em iOS lendo os documentos de Introdu\347\343o desta estante de livros de informa\347\365es detalhadas sobre desenvolvimento de aplicativos para iOS. O W3C: examine v\341rios padr\365es. O padr\343o XML \351 especialmente relevante para este artigo. A linguagem Objective-C: a Apple tem documenta\347\343o se voc\352 precisar revisar a sintaxe \372nica da Objective-C.

Desenvolvendo um aplicativo de bate-papo para iPhone do zero: (Jack D. Herrington, developerWorks, janeiro de 2011): aprenda o processo para desenvolver um aplicativo de bate-papo para o iPhone a partir do servidor at\351 a interface com o usu\341rio no front-end. Mais artigos desse autor (Jack Herrington, developerWorks, mar\347o de 2005-hoje): Leia artigos sobre Ajax, JSON, PHP, XML e outras tecnologias.

Iniciante em XML? Obtenha os recursos necess\341rios para aprender XML.
\301rea de XML do developerWorks: localize os recursos necess\341rios para avan\347ar em conhecimentos na arena XML, incluindo DTDs, esquemas e XSLT. Consulte a se\347\343o Biblioteca t\351cnica de XML para obter um intervalo amplo de artigos t\351cnicos e dicas, tutoriais, padr\365es e IBM Redbooks.

Certifica\347\343o XML da IBM: Descubra como se tornar um Desenvolvedor Certificado pela IBM em XML e tecnologias relacionadas. eventos t\351cnicos e webcasts do developerWorks : Mantenha-se atualizado em rela\347\343o \340 tecnologia nessas sess\365es.

o developerWorks no Twitter: Inscreva-se hoje para seguir os tweets do developerWorks. Podcasts do developerWorks: escute entrevistas e debates interessantes para desenvolvedores de software.

Demos On Demand do developerWorks:
Acompanhe demos que abrangem desde a instala\347\343o de produto e configura\347\343o para iniciantes at\351 funcionalidade avan\347ada para desenvolvedores experientes. Obter produtos e tecnologias

Mac App Store: efetue o download e instale aplicativos no seu Mac.

Vers\365es de avalia\347\343o de produto IBM: Fa\347a o download ou explore as vers\365es de teste on-line no IBM SOA Sandbox e entre em contato com as ferramentas de desenvolvimento de aplicativos e produtos de middleware do DB2\256, Lotus\256, Rational\256, Tivoli\256e WebSphere\256. Discutir

perfil do developerWorks: crie seu perfil hoje e configure uma watchlist. F\363runs de discuss\343o da zona de XML: Participe de qualquer uma das v\341rias discuss\365es relacionadas a XML.

A Comunidade do developerWorks: Entre em contato com outros usu\341rios do developerWorks e explore os blogs, f\363runs, grupos e wikis voltados para desenvolvedores. ***

Sobre o autor: Jack Herrington \351 engenheiro, autor e apresentador que mora e trabalha em Bay Area. \311 poss\355vel se manter atualizado em rela\347\343o ao seu trabalho e aos seus escritos em http://jackherrington.com.

Lucas Souza
Muito bom!
H\341 177 dias Responder

Mauricio Junior
Ol\341,
Gostaria de saber a possibilidade de passar as fotos com o touch, tem que mudar muita coisa? H\341 161 dias Responder

Thiago Santos
pra passar fotos vc pode usar os metodos touchesBegan e touchesEnded no controller. H\341 28 dias Responder


link

Andrew Koening

Undefined Behavior Versus Teaching
August 22, 2012
2 Comments

Last week, I asked readers to find the bug in the following code example:

const char* hello = "Hello"; 
const char* world = "world"; 
char* helloworld = new char[strlen(hello) + strlen(world) + 2];
strcpy(helloworld, hello);
strcat(helloworld, ", ");
strcat(helloworld, world);

One reader posted a comment that identified the bug: The 2 in the third line should be 3, in order to account for the comma (in the quotes on the fifth line), the space after the comma, and the null character that terminates C-style strings. There is actually a second bug, which went unmentioned: The memory to which helloworld points was allocated with a new expression, so at some point it must be freed with an appropriate delete[] expression.

A second reader made the following comment:

I can see advantages and disadvantages to starting instruction at the high-level and starting at the low-level. Part of it depends on your application area. \u2028

If you're a newly minted college grad with some C# or Java experience, you get to your first job and learn that you'll be doing a Linux driver for a new device the company is building. In such a case, though you want to make use of some C++ facilities, it doesn't necessarily move you along faster to start with std::string and std::vector because you need to know more about pointers and raw arrays in order to interface with the OS and the device.

This is an interesting comment, and one about which I think reasonable people can disagree. There is no question that people who intend to write device drivers need to understand low-level concepts thoroughly. However, I think there is definitely a question about the best way to reach that state of affairs.

I believe that even if the eventual goal is to show programmers how to write low-level code, it is still better to start at the top and work down. The trouble with code examples such as the one above is that all too often, they will appear to work \u2014 thereby giving the programmer the incorrect impression that the erroneous code is actually correct. Such misimpressions can take surprisingly long to unlearn.

When a program performs an operation, the language in which it is written can treat that operation in one of three ways:

The operation is well defined, so the program behaves according to the definition. The operation is defined to be invalid, so the program reports the error. The operation is not defined, so the program does something that may or may not be related to what the programmer intended. My experience is that not only is case (3) a rich source of bugs that are hard to trace, but it is also a serious impediment to learning. If a student writes X and the machine does Y, the student will typically conclude, "If I write X, the machine will do Y." It is only after much experience that students learn that the right conclusion might actually be, "If I write X, the machine will do something, which might or might not happen to be Y; I cannot draw any conclusions from what it happens to do."

This experience argues \u2014 at least to me \u2014 that in teaching programming, it is important to avoid situations in which students might be tempted to write undefined code that happens to appear to work. The example above is typical of such code: A student who writes it and gets what appears to be correct results will have no reason to suspect that anything is wrong.

In other words, a programmer who does something undefined does not always realize what has happened. In the strcpy case above, it is entirely possible that the memory that is improperly overwritten happens not to be used for any other purpose, so the program will appear to work. How can a programmer who writes such code come to realize that it is a mistake?

Even worse: It is not always possible to test reliably for undefined behavior. The widely held view that a program is correct if it passes all of its test cases simply does not apply when the program evokes undefined behavior.


Sencha

Blog
Search
HTML5 Scorecard: The New iPad and iOS 5.1
\u2014 A Mixed Bag
March 30, 2012 | Aditya Bansod

Apple\u2019s new iPad has a beautiful screen, but often struggles to smoothly display and scale even average webpages. This month, Apple released the \u201cnew iPad\u201d, its newest and latest tablet device, featuring a high resolution \u201cRetina Display\u201d, an updated CPU and GPU and more memory. A few weeks before the launch of the iPad, Apple also released iOS 5.1, a mostly maintenance release that included fixes for battery life among various others. 61% of devices are now upgraded to iOS 5.1.

Our HTML5 scorecard typically focuses on what HTML5 developers need to consider when developing for a platform or mobile operating system. Both the new iPad and iOS 5.1 are significant updates in the Apple ecosystem. In this HTML5 scorecard, we\u2019ll look at them independently, explore a few of the issues we found and give developers some guidance on how to work both the new iPad and with iOS 5.1.

In a nutshell, the new iPad is a mixed bag. The new iPad\u2019s display is incredibly fine grained and web site text now appears unbelievably sharp. On the other hand, the browser experience is noticeably slower with stutters and redraws on complex web pages and web apps. Images that haven\u2019t been updated for retina displays now appear blurry in contrast to the sharp text. iOS 5.1 doesn\u2019t offer many new features, and it does take a step backwards. For hybrid apps (web apps packaged in a native shell), iOS 5.1 breaks localStorage and WebSQL persistence, so developers can\u2019t rely on them anymore.

iOS 5.1

As has been widely reported by web developers, iOS 5.1 has changed the behavior of an embedded WebView. WebViews power HTML5 applications that live inside of native packages, such as PhoneGap or Sencha Touch native packaging. They provide an embedded web browser that is hosted within a native application, permitting the distribution of web apps to native app stores. WebViews are a feature of all modern mobile operating systems.

Prior to iOS 5.1, when an embedded WebView was used, data stored locally using HTML5 storage was kept persistent. Specifically, if your application used localStorage or WebSQL, it was considered part of the application\u2019s data. When a new version of the app was installed or the app was hard-closed, the persistent data was kept around. The next time the app started, the localStorage would appear as if it had never gone away, exactly as what happens in Mobile Safari.

In iOS 5.1, this data is no longer considered persistent and is treated as temporary or transitory data, so iOS can destroy it at any time, without warning, including during low memory scenarios. This is probably because Apple can\u2019t reliably iCloud backup, or iCloud sync from anything that\u2019s not stored in the native CoreData storage. As such, they\u2019re pushing developers to move to Apple native data systems to make apps iCloud-ready. Of course not everybody will want to do this. For developers who relied on localStorage or WebSQL as their mechanism to store data in their app, breaking this mechanism is a big deal. There are various workarounds, such as using the PhoneGap-SQLPlugin which uses the underlying SQLite, or writing your own JavaScript bridge to CoreData.

We also poked around iOS 5.1 to see if there were new HTML5 features like CSS regions or support for the File API or any other new web platform features. We used our favorite tool, haz.io which builds on the open source Modernizr detection library to see what\u2019s new under the hood. In short: nothing. No new features showed up between iOS 5.0 and iOS 5.1. iOS still features some of the best HTML5 support on any mobile browser, but this latest incarnation hasn\u2019t increased the depth of Mobile Safari\u2019s support for the standards. We\u2019re hoping to see CSS Regions come to iOS soon, as it\u2019s supported in Safari 6. Mobile Safari reports \u201c5.1\u201d as its version number, so it\u2019s likely only a matter of time until we get the ability to use the Regions feature. We were also looking to see if WebGL, which is currently only available for Apple iAds, is available in the public browser. haz.io reports that WebGL is supported in Mobile Safari, but when we used the Khronos demo repository to test, we were unable to get any of the demos to work.

For the HTML5 developer out there, heed the warnings when using localStorage or WebSQL in a packaged app on iOS 5.1, and don\u2019t expect any new HTML5 features in iOS5.1 Mobile Safari.

Retina iPad

For HTML5 developers, the most obvious thing about the Retina Display iPad is the huge number of pixels that the device now manages. The new iPad sports a resolution higher than a 1080p television. User interfaces are doing more than 4x the work pushing all the new pixels around. The new iPad houses an Apple A5X CPU together with a PowerVR SGX543MP2. The A5X is a dual core ARM-Cortex A9 design, running at 1GHz, and the GPU is a quad-core design running in roughly the same graphics class as the Nvidia Tegra line. From what we can tell, the main difference between the A5 (which powers the iPad 2 and the iPhone 4S) and the A5X is the new quad-core GPU. Given the new pixel density, it stands to reason that it\u2019s the most upgraded component of the new iPad\u2019s processing subsystem.

Since we\u2019re focusing on HTML5 developers, we focus on web benchmarks for performance. We re-ran the iPad 2 with iOS 5.1 along with the new iPad with iOS 5.1 and found a set of interesting results. As usual, we turned to SunSpider and the V8 Benchmark Suite for raw JavaScript processing power. We found (and perhaps given the new display\u2019s tax on the whole system this is unsurprising) that new iPad was marginally slower than the iPad 2. The SunSpider score is about 150 points slower than the iPad 2, and the V8 Benchmark was 45 points slower. We ran the tests a few times and while the specific numbers were a bit different each time the overall result was the same: on pure JavaScript processing, the new iPad is slower than the iPad 2.

SunSpider v0.91 Results, smaller is better.

V8 Benchmark Suite v6, bigger is better. We then turned our attention to some complex web sites and apps to see how the new iPad performed with graphics. We turned to our Sencha Animator Kickfu demo, which is a very complex CSS3 animation, and were pleased that it ran reasonably well. Wanting to push it a bit further, we decided to pinch-zoom in and try to play the game again and this time we saw an immense amount of tiling occurring. This severe tiling seems to have been introduced in iOS 5, so it\u2019s not a new iPad thing, but definitely an artifact introduced in newer iOS\u2019 that hasn\u2019t gotten better with new hardware.

Our tests always include Canvas, and we tested our two current favorite Canvas apps, Canvas Rider and Canvas Cycle. Both of them test the CPU/GPU and the browser\u2019s Canvas drawing engine. The new iPad does fine here, rendering both of these examples with the same performance as the iPad 2. Given how fast the iPad 2 is, it\u2019s impossible to visually discern any difference in Canvas performance between the two devices.

In general web browsing, we did notice one notable difference between the iPad 2 and the new iPad. It draws much more slowly on complex pages. For example, on the Ext JS examples page, when scrolling the page, it visibly loads in new tiles at the bottom of the page while moving. Also, when zooming in on image rich pages such as our Sencha Touch 2 product page, the same tiling behavior occurs again that rarely occurred on the iPad 2. It\u2019s clear that this is due to the the new Retina Display. It\u2019s very likely that images and other assets being transferred to the GPU are taking more time (and bus bandwidth) than the device can handle in real time.

We\u2019re definitely not hardware or chip experts here, but we figured we\u2019d dig a little with the iFixit breakdowns to see why this might happen and if were parts on the new iPad that were not upgraded to match the new resolution. The iPad 2 uses an Apple A5 System on a Chip, which includes 512 MB of DDR2 RAM in the SoC package. Compare that to the new iPad which has an A5X SoC, which does not include the memory in the SoC package. Rather there are two 512 MB Elpida DDR2 chips. The new iPad has two times the memory, and four times the pixels to push, but runs the memory bus at the same speed as the iPad 2. Again, we\u2019re not experts on embedded systems design, but it stands to reason that some of the graphics performance issues we are seeing, (especially tiling and performance degradation from box shadows) might be caused by this system imbalance. po The New iPad and iOS 5.1: tips for the HTML5 developers

We\u2019re usually effusive about the latest mobile browser and hardware from Apple. But this latest offering is a mixed bag at best and a disappointment at worst. For the last few years, we\u2019ve grown accustomed to Apple leapfrogging the competition each year with superior hardware and even better HTML5 browser software. The latest set of Apple hardware has regressions compared to the iPad 2 including slower JavaScript performance. And with iOS 5.1, the removal (or breaking) of features that developers have trusted is a real letdown. While we believe that the iPad is still the best tablet in the market, it\u2019s the first time a new Apple product hasn\u2019t categorically outshone its predecessor. Particularly for business applications, there is no reason to choose the new iPad over the iPad 2.

Written by Aditya Bansod

Aditya is Sencha's senior director of product management and is responsible for the product planning and strategy for Sencha's product lines. Prior to Sencha, Aditya held various senior product management roles at Adobe and Microsoft, focusing on developers and media in the mobile and consumer electronics space. Follow Aditya on Twitter

Related Posts
Sencha Touch oData Connector and Samples for SAP
A Survey of JavaScript Timers on Mobile
HTML5 Scorecard: RIM BlackBerry PlayBook OS 2.0
Share this post:Share on twitter Share on facebook Share on stumbleupon Share on linkedin Share on delicious Share on reddit Leave a reply


Ibovespa estende perdas e inicia preg\343o em queda

Merkel diz querer a Gr\351cia na Zona do Euro, mas espera relat\363rio da Troika; pedidos de bens dur\341veis nos EUA superam expectativas

Por Fernando Ladeira |10h12 | 24-08-2012 A A A

S\303O PAULO - Em linha com o cen\341rio internacional, o Ibovespa estende as perdas do \372ltimo preg\343o, quando recuou 1,46%, e inicia os neg\363cios desta sexta-feira (24) em queda de 0,80%, aos 58.042 pontos. Nem mesmo a melhora nos pedidos de bens dur\341veis nos EUA em julho, que superaram as expectativas ao avan\347arem 4,2% sobre o \372ltimo m\352s, animou o mercado.

Isso acontece depois da chanceler alem\343 Angela Merkel reiterar, em entrevista coletiva junto com o primeiro-ministro grego Antonis Samaras, que quer a perman\352ncia da Gr\351cia na Zona do Euro. Entretanto, Merkel alertou que precisa ver o relat\363rio da Troika - grupo formado por Comiss\343o Europeia, FMI (Fundo Monet\341rio Internacional) e BCE (Banco Central Europeu) - antes de decidir sobre concordar com mais tempo para que a Gr\351cia cumpra com as reformas prometidas.

Principais baixas

Entre as principais quedas do Ibovespa nesta manh\343, destaque para as a\347\365es da Usiminas (USIM5, R$ 8,41, -3,33%), Lojas Renner (LREN3, R$ 64,22, -3,15%), CSN (CSNA3, R$ 11,22, -2,86%), B2W Varejo (BTOW3, R$ 7,45, -1,97%) e Bradespar (BRAP4, R$ 27,29, -1,76%).

Notici\341rio europeu movimentado

Por sua vez, a chanceler alem\343 disse estar convicta que o governo grego est\341 comprometido em resolver os problemas do pa\355s. J\341 Samaras refor\347ou que n\343o pedir\341 por mais recursos e apelou para mais tempo no cronograma, de modo a restaurar o crescimento em um pa\355s que se encontra em grave recess\343o. No s\341bado ser\341 a vez de Fran\347ois Hollande, presidente franc\352s, se encontrar com Samaras.

No front econ\364mico, o escrit\363rio de estat\355sticas do Reino Unido mostrou uma contra\347\343o de 0,5% no PIB (Produto Interno Bruto) do segundo trimestre. Anteriormente, a proje\347\343o era de uma queda de 0,7% na economia brit\342nica. Al\351m disso, a agenda econ\364mica \351 pouco movimentada, apenas com dados sobre os pedidos de bens dur\341veis nos EUA, a ser divulgado \340s 11h00 (hor\341rio de Bras\355lia). Mercado dividido sobre est\355mulos

Al\351m disso, os investidores tamb\351m est\343o receosos com as promessas de novos est\355mulos econ\364micos, tanto na Europa quanto nos EUA. Mohamed El-Erian, CEO da maior gestora de renda fixa do mundo, a Pimco, alertou no final de quinta-feira que a quest\343o agora \351 se os pol\355ticos europeus conseguir\343o passar das palavras para a\347\365es concretas e, enfim, trazer a tranquilidade para os mercados.

Nos EUA o temor \351 com a nova rodada de est\355mulos. Depois da ata do Fomc (Federal Open Market Committee) mostrar que mais recursos dever\343o ser injetados na economia se esta n\343o der sinais de melhora, os norte-americanos se mostram divididos sobre o pr\363ximo passo. Na v\351spera, enquanto o presidente do Federal Reserve de St. Louis, James Bullard, disse que essa medida encontrar\341 grandes obst\341culos, Bill Gross, da Pimco, disse que o afrouxamento "j\341 est\341 certo". No Brasil, mais incentivos

Por aqui, o destaque fica por conta da prorroga\347\343o em mais dois meses na redu\347\343o do IPI (Imposto sobre Produtos Industrializados), conforme publicou a Folha de S. Paulo nesta manh\343. O an\372ncio oficial dever\341 acontecer na pr\363xima semana, quando o benef\355cio est\341 programado para chegar ao fim.


Dica do dia: pr\351-visualizando fontes em apps nativos para o OS X 1 coment\341rios postados
Atualizado: 23/08/2012 \340s 13:36por Rafael Fischmann
23/08/2012 \340s 13:36

Detalhe t\355pico da Apple: sabe aquele pontinho que fica no topo da janela de sele\347\343o de fontes, em apps nativos do OS X? Pois saiba que d\341 pra \u201cpux\341-lo\u201d para baixo e, assim, abrir uma pequena \341rea de pr\351-visualiza\347\343o (preview) das suas tipografias. Muito, muito \372til! [Cult of Mac]


Como esperado, Apple tamb\351m libera primeiro build de testes do OS X 10.8.2 para desenvolvedores 2 coment\341rios postados
Atualizado: 23/08/2012 \340s 13:09por Rafael Fischmann
23/08/2012 \340s 13:09

Conforme adiantamos ontem, a Apple disponibilizou hoje para desenvolvedores o primeiro build (12C31a) de testes do OS X 10.8.2 \u2014 logo ap\363s o lan\347amento oficial da primeira atualiza\347\343o do Mountain Lion para o grande p\372blico. Sem problemas conhecidos, o update \u2014 cuja vers\343o Combo por enquanto pesa 641,83MB \u2014 se foca em Messages, Facebook(!), Game Center, Safari e Lembretes (Reminders). Ele provavelmente ser\341 lan\347ado para todos junto ao iOS 6, no m\352s que vem.


link

Dica: substitua s\355mbolos e texto facilmente no OS X atrav\351s de atalhos program\341veis
[atualizado]
10 coment\341rios postados
Atualizado: 23/08/2012 \340s 17:56por Eduardo Marques
23/08/2012 \340s 10:40

O sistema operacional da Apple oferece um recurso muito bom para quem est\341 sempre repetindo/escrevendo as mesmas informa\347\365es: trata-se da substitui\347\343o de s\355mbolos e texto. Basta entrar em Prefer\352ncias de Sistema (System Preferences) \273 Idioma e Texto (Language & Text) e escolher a aba Texto (Text). Depois disso, voc\352 ver\341 a janela abaixo:

Agora, basta clicar no sinal de mais (+), adicionar o que voc\352 quiser, colocando o atalho na coluna \u201cSubstituir\u201d (Replace) o s\355mbolo/texto na coluna \u201cCom\u201d (With) e ativar. Como podemos ver, a Ma\347\343 j\341 nos oferece algumas op\347\365es por padr\343o, mas ela n\343o necessariamente atende \340s necessidades de todos.

Mas a dica de ouro, dada por Adam Dachis, do Lifehacker, \351 colocarmos v\355rgulas antes de palavras chaves, facilitando muito nosso trabalho. Veja tr\352s simples exemplos, abaixo: Claro que voc\352 pode utilizar outra marca\347\343o al\351m da v\355rgula, mas o intuito aqui \351 deixar a coisa r\341pida/pr\341tica, facilitando o trabalho. Se voc\352 j\341 utiliza ou pretende fazer o uso desse recurso, compartilhe conosco (e com outros leitores) seus atalhos, afinal, quanto mais ideias, melhor! :-) ATUALIZA\307\303O

O leitor Gustavo Michels lembrou bem: para fazer funcionar em alguns aplicativos nativos, \351 preciso habilitar o recurso. No campo de texto do Mail ou do Safari, por exemplo, clique com o bot\343o direito, escolha a op\347\343o Substitui\347\365es (Substitutions) e marque a op\347\343o Substitui\347\343o de Texto (Text Replacement). Dessa forma, o recurso funcionar\341.


link

Dica Git da Semana: GC e Pruning

sexta-feira, 24/08/2012 \340s 11h08, por Alex Blewitt

Paul Webster escreveu \u201cWhere the git did that go?\u201d em rela\347\343o ao incr\355vel desaparecimento de commits. Alguns disseram que um sistema de controle de vers\343o n\343o deve ser capaz de fazer isso, mas na verdade tudo faz parte da funcionalidade do Git. Vejamos o que aconteceu.

Um reposit\363rio Git armazena commits em uma closure transitiva (uma closure real, n\343o um lambda) a partir dos itens acessados atrav\351s de cada commit (e cada tree e blob). N\343o \351 poss\355vel remover um commit \u2013 e, portanto, as trees e os blobs que comp\365em esse reposit\363rio.

Ent\343o, como \351 poss\355vel perder dados com Git? Bem, se voc\352 estiver usando um reposit\363rio Git padr\343o, voc\352 pode criar branches com git branch, e exclu\355-los com git branch-d. Quando voc\352 exclui um branch, voc\352 remove o ponteiro para o \372ltimo commit \u2013 mas na verdade voc\352 n\343o os perde.

Al\351m disso, o git reflog, que abordamos anteriormente, armazena uma lista dos ponteiros do branch anterior. Em outras palavras, mesmo se voc\352 excluir um branch, o reflog te defende.

No entanto, de um modo geral, apenas reposit\363rios com diret\363rios em funcionamento possuem reflogs; poucos reposit\363rios tendem a n\343o ter. H\341 uma op\347\343o de configura\347\343o, git config core.logAllRefUpdates, que pode ser usada para for\347\341-lo em todos os reposit\363rios \u2013 ou desativ\341-lo completamente caso n\343o seja necess\341rio.

Mesmo sem um reflog, os commits n\343o s\343o removidos imediatamente. Se voc\352 executar um git gc, que empacota novamente o reposit\363rio para uma estrutura mais eficiente, ele vai exportar commits n\343o referenciados como objetos soltos. (Voc\352 tem que garantir que n\343o existem quaisquer branches ou tags ou reflogs para ver esse comportamento; se h\341 um ponteiro existente, ent\343o ele n\343o ir\341 expulsar o objeto do packfile.)

Executar um git fsck vai verificar que todos os objetos est\343o presentes como esperado. Voc\352 tamb\351m pode visualizar o que n\343o \351 mais referenciado; executar git fsck \u2013unreachable vai te mostrar quais commits n\343o est\343o mais acess\355veis devido aos branches eliminados ou \340s tags removidas. Executar git fsck \u2013unreachable diariamente e relat\363rios di\341rios vai te dar um bom alerta do commit que est\341 em vias de extin\347\343o, caso isso seja uma preocupa\347\343o.

Os objetos que n\343o s\343o mais referenciados podem ser removidos com git prune; embora essa seja uma opera\347\343o de n\355vel inferior, que muitas vezes \351 chamada de git gc. Por padr\343o, ela n\343o remover\341 commits mais novos do que duas semanas de idade e, claro, os commits que est\343o acess\355veis a partir disso; ent\343o, fornecido o branch (ou tag) eliminado que possui commits recentes, ele permanecer\341 em torno do reposit\363rio git por at\351 duas quinzenas.

Evitando problemas futuros

Ambos branches e tags podem ser apagados, e ao invocar uma opera\347\343o push remota de um branch ausente (ou tag) no lado do cliente pode invocar um delete; por exemplo: git push github :refs/heads/master vai apagar o branch \u2018master\u2019 fora do reposit\363rio remoto conhecido como github. Se isso for em um script, como git push github $COMIT:refs/heads/master e a vari\341vel est\341 incorreta (portanto, avaliada como a string vazia), isso pode inadvertidamente excluir o branch. (O mesmo \351 verdadeiro para as tags em: :refs/tags/.)

Um reposit\363rio remoto pode desativar essas opera\347\365es com a configura\347\343o receive.denyDeletes para impedir qualquer ref deletion, e evitar branches n\343o-fast-foward com o receive.denyNonFastforwards. Se qualquer um desses for estabelecido, ent\343o as exclus\365es n\343o ter\343o nenhuma opera\347\343o e pushes n\343o podem substituir o c\363digo que n\343o segue estritamente o hist\363rico. (Isso \351 ocasionalmente uma opera\347\343o \372til; \351 prov\341vel que seja necess\341rio proporcionar um meio para elev\341-la em certas situa\347\365es.)

Al\351m disso, assegurar que os branches t\352m core.logAllRefUpdates ir\341 garantir que o reposit\363rio ainda mant\351m o hist\363rico dos branches, pelo menos para os dias de gc.reflogexpire e de gc.reflogexpireunreachable.

Resumo

Enquanto o git pode ser usado, h\341 op\347\365es poderosas que podem ajustar ou restringir o seu comportamento. Diante de scripts que t\352m pleno acesso ao reposit\363rio remoto, \351 aconselh\341vel ter um conjunto mais controlado de op\347\365es em vez do padr\343o \u201cvoc\352-pode-fazer-qualquer-abordagem\u201d. Com esse conhecimento em mente, voc\352 poder\341 definir as suas op\347\365es de forma adequada para seu ambiente.

*** Texto original dispon\355vel em http://alblue.bandlem.com/2011/11/git-tip-of-week-gc-and-pruning-this.html

Alex Blewitt
\351 guru em Eclipse e fan\341tico pelo Mac.
P\341gina do autor Email
Leia os \372ltimos artigos publicados por Alex Blewitt

Dica Git da Semana: GC e Pruning

Dica Git da Semana: Git Notes

Dica Git da semana: Revendo Merging

Dica Git da semana: Revendo \315ndices Dica Git da Semana: entendendo o \355ndice


link

Como criar um Proxy transparente com Nginx sexta-feira, 24/08/2012 \340s 10h08, por Thiago Avelino

Muitas pessoas usam o Squid para fazer qualquer tipo de proxy \u2013 ate mesmo para proxy transparente para usar em servidor web. Por exemplo: Voc\352 tem um site que precisa ter IP aqui no Brasil, mas como o custo de servidor e link aqui no Brasil \351 muito caro, voc\352 pode fazer um proxy transparante para o servidor aqui no Brasil ser um cara que vai receber a requisi\347\343o e repassar para o outro servidor que esteja em qualquer lugar do mundo. Com essa solu\347\343o, podemos ter uma m\341quina simples (com pouco poder de processamento) pois ela s\363 vai receber o tr\341fego e repassar para o servidor que vai estar em outro local.

Vamos imaginar um exemplo pr\341tico. Preciso que o usu\341rio acesse o IP 177.71.248.185 (\351 um servidor da Amazon no Brasil). Esse servidor precisa receber a requizi\347\343o e repassar para o IP 67.159.35.2 (\351 a maquina principal onde \351 processado o backend \u2013 esse servidor esta fora do Brasi). Foi usado essa solu\347\343o em um portal que atendo para ter baixa latencia.

Vamos ao exemplo pr\341tico:

 
upstream server {
server 67.159.35.2;
}
server {
listen 80;
server_name avelino.us www.avelino.us;
location / {

proxy_cache proxy-cache;
proxy_cache_key \u201c$host$request_uri$args\u201d;
proxy_ignore_headers \u201cCache-Control\u201d \u201cExpires\u201d;
proxy_cache_min_uses 1;
proxy_hide_header Set-Cookie;
proxy_cache_valid 200 301 302 30m;
proxy_cache_valid any 0m;
proxy_buffering on;

proxy_pass http://server;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

}

Criei um \u201cupstream server\u201d para falar qual \351 o servidor de destino do trafego, Na configura\347\343o acima tem um cache de 30 minutos, pois no servidor principal tem cache de quatro horas.

Logicamente que existe desvantagem com isso, pois estaremos trafegando em duas (ou mais) rede, assim usando o tr\341fego do servidor que est\341 recebendo a primeira requisi\347\343o e do segundo, que esta recebendo um requisi\347\343o do primeiro.

Thiago Avelino trabalha com web e software livre. Desenvolve aplica\347\365es em Python, Django e MongoDB. Participa da comunidade Python, contribui com a tradu\347\343o da documenta\347\343o do MongoEngine e MongoDB e presta consultoria atrav\351s de sua empresa. Twitter: @avelino0.

P\341gina do autor Email
Leia os \372ltimos artigos publicados por Thiago Avelino

Como criar um Proxy transparente com Nginx

Como criar um console colorido, usando Node.js Criando package (m\363dulo) em Node.js Criando um servidor FTP com Python Criando um servidor HTTP (Web) com Python


link

Integrating JavaFX 2.x and Swing: It's Simple
August 24, 2012
Post a Comment

With JavaFX 1.x, it was possible to embed Swing controls into a JavaFX application, but officially it wasn't possible to do the reverse. Although Sun/Oracle didn't support it, clever people found a way around this (read my past writing on the subject if you're interested). However, it quickly became evident that many people had large, complex Swing applications that they weren't willing or capable of entirely refactoring as a JavaFX application. So, Oracle added the ability to embed JavaFX components (built-in controls, custom controls, as well as entire JavaFX Scenes) inside a Swing application. With the JavaFX 2.x JFXPanel class, the one class needed to accomplish this, you can host JavaFX components alongside Swing components within a Swing JPanel, for instance. Let's look at how this works conceptually:

Containment model:

 
JPanel <>--- JFXPanel <>--- Scene <>--- Group <>--- javafx.control.*
Or, in pseudocode:


JPanel.add(JFXPanel.setScene(Scene.setRoot(Group.getChildren().add( javafx.control ))));

JPanel.add(JFXPanel.setScene(Scene.setRoot(Group.getChildren().add( javafx.control )))); That may look complicated, but it's really not. You set up the JavaFX Scene relationship as usual, with no need for a Stage since the Swing application will act as your stage. Instead, create your JavaFX container (HBox, VBox, or Group, and so on), set it as your Scene's Root (or Parent), then add JavaFX controls to that root container. Finally, add the Scene to a special JFXPanel class, whose only role in life is to be placed within a Swing container (i.e., a JPanel) and serve as a bridge between the two worlds \u2014 a wormhole, if you will. Voila\u2026 Swing/JavaFX integration in a nutshell.

A Working Example

As an example, let's take the really cool SizeView container I created with JavaFX 2.x a few months ago. This custom container allows you to place any number of JavaFX controls within it, where each are separated by a sizing bar. When you resize one component, the others adjacent to it resize accordingly. Learn all about the control and resizing algorithms from my past blog .

The code is below. The explanation is this:

  1. The Swing application starts

  2. A JFrame is created and sized

  3. The SwingFX2 class (which extends JPanel) is instantiated and added to the JFrame

  4. In the constructor, initComponents is

  5. called, where the following steps occur:

The application, when run, looks like this:

For the official Oracle tutorial on the JFXPanel class, go here .

 
Happy Coding! 
-EJB public class SwingFX2 extends JPanel { // It's a Swing JPanel private JFXPanel jfxPanel; // The JavaFX component(s) private JButton swingButton; // The Swing component public SwingFX2(){ initComponents(); } public static void main(String ...args){ SwingUtilities.invokeLater(new Runnable() { public void run() { // Create a Swing Frame final JFrame frame = new JFrame(); frame.setMinimumSize(new Dimension(640, 480)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add the Swing JPanel and make visible frame.getContentPane().add(new SwingFX2()); frame.setVisible(true); } }); } private void initComponents(){ // The JavaFX 2.x JFXPanel makes the Swing integration seamless jfxPanel = new JFXPanel(); // Create the JavaFX Scene createScene(); setLayout(new BorderLayout()); add(jfxPanel, BorderLayout.CENTER); swingButton = new JButton(); swingButton.addActionListener( new ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent ae) { System.exit(0); } }); swingButton.setText("Close"); add(swingButton, BorderLayout.SOUTH); } private void createScene() { // The Scene needs to be created on "FX user thread", NOT on the // AWT Event Thread PlatformImpl.startup( new Runnable() { public void run() { Group root = new Group(); Scene scene = new Scene(root, 80, 20); SizeView sizeview = createSizeView(scene); root.getChildren().add(sizeview); jfxPanel.setScene(scene); } }); } private SizeView createSizeView(Scene scene) { double HBOX_WIDTH = scene.getWidth() - 10 - 10; final SizeView sizeview = new SizeView(); sizeview.setLayoutX(10); sizeview.setLayoutY(10); sizeview.setPrefWidth(HBOX_WIDTH); Node[] controls = new Node[5]; for ( int l = 0; l < controls.length; l++ ) { controls[l] = new ListView(); } sizeview.getChildren().setAll(controls); scene.widthProperty().addListener( new ChangeListener() { public void changed(ObservableValue observable, Object oldValue, Object newValue) { Double w = (Double)newValue; sizeview.setPrefWidth( w - 20 ); sizeview.layout(); } }); return sizeview; } }

hr color="#0099FF">

Apple \351 processada por ex-empregado respons\341vel por criar as keynotes de Steve Jobs
7 coment\341rios postados
Atualizado: 21/08/2012 \340s 09:33por Eduardo Marques
21/08/2012 \340s 08:47

tr As Stevenotes eram, sem d\372vida, o ponto alto de qualquer evento da Apple. N\343o s\363 pela desenvoltura, dom\355nio de palco e do famoso Campo de Distor\347\343o da Realidade\256 do cofundador e ex-CEO da Apple, como tamb\351m pelas impec\341veis apresenta\347\365es em si (o Keynote que ficava rodando no tel\343o).

Mas engana-se quem acha que Steve Jobs as preparava sozinho. De acordo com a Bloomberg, Wayne Goodrich eram quem cuidava disso tudo, ajudando o ex-chef\343o da Ma\347\343 a pensar em todos os detalhes. Jobs valorizava tanto o trabalho de Goodrich que teria garantido o emprego dele logo depois de voltar de uma das licen\347as m\351dicas que tirou durante sua gest\343o. Contudo, em dezembro passado, pouco depois da morte do ex-CEO, Goodrich foi demitido por \u201craz\365es de neg\363cios\u201d, de acordo com seu advogado.

Exatamente por isso, Goodrich est\341 processando a Apple. Alegando quebra de contrato e pr\341ticas comerciais desleais, ele pede uma indeniza\347\343o pelas perdas de a\347\365es restritas, sal\341rios, benef\355cios e desconforto emocional. Procurado para comentar o assunto, Steve Dowling, porta-voz da Apple, se recusou a falar.

Ser\341 que n\343o dava para Goodrich continuar fazendo as keynotes, agora apresentadas por Tim Cook e companhia? Ou ser\341 que algum dos grandes executivos assumiu essa responsabilidade?