Technology


3
Jun 14

“Swift” is Syntactic Sugar

download The “new” Swift programming language from Apple is nothing more that syntactic sugar on top of Javascript.

A few examples from Swift Welcome page and Swift Tour page

Example 1:

Swift code:

============================
let people = ["Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25]
for (name, age) in people {
println("\(name) is \(age) years old.")
}
==============================

JS code ( http://jsfiddle.net/SSD9Y/1/ ) :

============================
var people = {"Anna": 67, "Beto": 8, "Jack": 33, "Sam": 25}

for ( person in people ) {
alert( person + " is " + people[person] + " years old.")
==============================

Example 2:

Swift code:

============================
let cities = ["London", "San Francisco", "Tokyo", "Barcelona", "Sydney"]
let sortedCities = sort(cities) { $0 < $1 }
if let indexOfLondon = find(sortedCities, "London") {
println("London is city number \(indexOfLondon + 1) in the list")
}
==============================

JS code ( http://jsfiddle.net/pYWb9/1/ ) :

============================
var cities = ["London", "San Francisco", "Tokyo", "Barcelona", "Sydney"]
var sortedCities = cities.sort()

indexOfLondon = sortedCities.indexOf("London")+1
alert("London is city number " + indexOfLondon + " in the list")
==============================

Example 3:

Swift code:

============================
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
==============================

JS code ( http://jsfiddle.net/p3FM6/1/ ):

============================
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations= {Malcolm: 'Captain',Kaylee:'Mechanic'}
occupations["Jayne"] = "Public Relations"
==============================

Example 4:

Swift code:

============================
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore
==============================

JS code ( http://jsfiddle.net/s9DF5/1/ ):

============================
var individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for (score in individualScores) {
if (score > 50) {
teamScore += 3
} else {
teamScore += 1
}
==============================

25
Apr 11

Os Recém Convertidos

(NOTA: este artigo foi publicado aqui na Exame Informática, na minha coluna de opinião Franco Atirador; para a semana há mais)

 

Não há nada pior do que um recém convertido. Desde os zelotas sicários até aos fanáticos religiosos dos nossos dias, foram sempre os recém convertidos que tiveram as atitudes mais extremistas e fanáticas.

Não há nada pior do que um recém convertido à religião da Apple e do seu Deus, Steve Jobs.

Não tenho rigorosamente nada contra o Steve Jobs. É um génio de marketing (mais do que tecnológico) que há muito tempo admiro. Tirando o ZX81, o ZX Spectrum, o Commodore 64 e um PC Amstrad 1512, os primeiros computadores que usei na Faculdade foram Macs (o Classic). Na altura fiz alguns trabalhos numa NeXT workstation (a melhor coisa que o Steve Jobs alguma vez fez e que 20 anos depois continua a ter coisas melhores do que os MacOSX e os Windows que por aí andam). Tenho uma NeXT em casa. Acho que isso diz tudo.

Não tenho rigorosamente nada contra a Apple. É uma empresa fantástica que faz sair produtos de excelência. Uma das empresas de que sou sócio, envolvida no negócio do design e comunicação gráfica, trabalha desde 1996 com Macintosh, desde o tempo dos Quadras e dos Power Macintosh, e correu os modelos todos até aos mais recentes.

O que me chateia são os recém convertidos à “religião” do Macintosh.

Durante anos não se via um Mac numa faculdade. “Por questões de compatibilidade”, diziam. “Ao fim e ao cabo depois nas empresas é o que se usa”. Isto foi a tanga que foram dando. Eram zelotas dos Windows e da Microsoft. Até que o Mac se tornou moda. A partir do momento que se tornou moda “apreciar” o design e a facilidade de uso, que já eram um facto desde a década de 80, começaram os ratos a saltar do barco Microsoft. E agora é ver a proliferação de Macs nas Universidades. E a forma sobranceira como passaram a tratar os colegas que têm um PC com Windows. São uns info-excluídos coitados.

Depois há os convertidos tecnológicos. Sabem alguma coisa mais sobre computadores do que o utilizador normal. E também entraram na moda. Diz-me um no outro dia: “não sabes o que é bom”. Um palhaço a ensinar o Padre Nosso ao vigário… E para esses não há mais nada. Só existe a Apple. Durante anos tiraram MCSEs e foram para a fila nas FNAC quando saía a nova versão do Windows. Agora vão para a fila quando sai a última novidade da Apple. Mesmo que seja igual à anterior mas com mais cores.

Ainda piores são os convertidos tecnológicos que sabem bastante mais do que os utilizadores normais. Programadores, administradores de sistemas, etc. Durante anos fizeram cruzadas contra a Microsoft. “Bandidos!”. O software era proprietário, as aplicações uma porcaria, eram monopolistas e abusadores. Bom era o Linux, isso sim. Podia ter-se controle total sobre o sistema operativo e sobre o hardware. Mas agora que usam Macs o problema já não existe. A Apple é ainda mais proprietária, mais abusadora e os Macs computadores mais fechados. Mas está tudo bem. Ainda têm a lata de dizer que “não se querem preocupar com o computador, só querem que funcione”. Incoerência e falta de moral. Durante anos o Mac era para os designers, para as meninas e para os básicos. Mas agora já serve. Está na moda. Dá status…

Eu desfiz-me dos dois, dos Windows e dos Macs. Passei a usar Linux em todas os meus computadores (o telemóvel é Android, claro). O que teve uma grande vantagem: quando vem a família e os amigos pedir suporte técnico à borla posso dizer “Não uso, uso Linux, já não sei como isso funciona”. Temos pena.


28
Jan 10

Panopticlick and Browser Tracking

Worried about privacy and sites tracking you even though you have cookies disabled? ( https://panopticlick.eff.org/ )

Solving this is pretty simple, forget about disabling Javascript, uninstalling fonts and other complications: just change the User Agent string ( http://is.gd/7db0G ) to something random (or your fullname).

If you want to do it in Chrome forget about hex editing files nonsense. Just run Chrome like this: chrome –user-agent=”Mario Valente User Agent”

Result: “Your browser fingerprint appears to be unique among the 77,330 tested so far.”


13
Jan 10

The Flash vs JS/Canvas discussion

Some months ago:

“mvalente: Pq Flash vai morrer: acessibilidade, UI diferente, SEO, -speed. E pq js+css faz tudo”

“mvalente: Nao discuto :)… Em 5 anos o Flash vai estar no mm “nicho” em q estao as Java applets (ie. +- nulo)”

“mvalente: Who needs AIR, Flash, Silverlight, JavaFX and other crap http://is.gd/bKQb JS + Canvas, baby”

Feel free to search for Flash in my twitter archive (starts in March 2007 ends in February 2009; I dont chat on twitter anymore) http://mvalente.eu/Files/mvalentetwitterhistory.html


25
Nov 09

Requirements for a Modern Web Development Framework

For the last 2 years or so I have been harping about a Future Web Development Framework and about how Javascript Will Save Us All. And even 2 years before that (4 years ago) I had actually come to the conclusion that Javascript would be the next big language and the one that would invest my time in for the next 10 years (2005-2015).

Aditionally, 2 years ago I hinted at the need and possibility that Javascript should be used at in all of the tiers of aplication development. And 1 year ago, at Codebits, I restated the need for a totally Javascript-based, REST-accessible, JSON-formatted web development framework. I tried to challenge people at Codebits to work in it, but no such luck. I also tried to start developing it but it was a no go: I dont have as much patience for coding as I used to (age is a bitch) and the context for serverside Javascript development just wasnt right (lack of standards, lack of OS API access, etc). And even having some Javascript interpreters (like jslibs which is what I was using at the time) with access to stuff like files and sockets wasnt much of a help: its not very much fun to try and reinvent the wheel writing a webserver from the (socket) ground up.

Well, things have changed a lot in this past year. The ServerJS/CommonJS group has been doing a lot of work on standardising a unified JS API. And there’s been a lot of work done on top of several Javascript interpreters/compilers/VMs (like Spidermonkey, Rhino, V8, etc) to provide for basic system level functionality. Plus a lot of Javascript-based basic blocks have been developed (like Narwhal, Nitro, Node, Awesome, Lawnchair, DjangoDE, PURE, etc) that allows us to get more concrete about what is needed and what can be done.

So its time to once again tell the Lazyweb what I think is needed or (better yet) what I want in a new web development framework that lasts for 10 years. Here goes:

  • I want it to be Javascript based. All of it. No Erlang, Python, Ruby, etc in sight. I want the frontend/View/presentation in Javascript. I want the appserver/Controller/logic in Javascript. I want to program the appserver in Javascript. I want the DBserver/Model/data in Javascript.
  • I want all the Javascript code to be compliant with the CommonJS standards. The code should be portable to any of the existing engines (Spidermonkey, Rhino, V8, flusspferd, Jaxer, Helma, etc) although I would touch anything Java-based with a long pole, so please make it work on Spidermonkey or V8.
  • I want all the data to be JSON formatted and REST-accessible. The data on the database should be stored as JSON data and accessible via REST. The appserver API should be REST-based, accept JSON-formatted parameters and return JSON-formatted results. The templating system should accept JSON-formatted data for rendering the view and make REST JSON-formatted calls to the appserver.

If this isnt clear enough, let me refer some analog components that are written in other languages and what is already available in JS:

  • for the database I want CouchDB but written in Javascript. Awesome or Lawnchair might be starting points. The endpoint would be something like Persevere but without the Java/Rhino dependency. Maybe Pintura is *it*…
  • for the appserver I dont have the right analog. Of course that it must support JSGI. But *the* most important thing: it can not and must not allow the generation of HTML and the return of HTML to the browser/client! All methods/functions should only accept parameters and return results in JSONified format. Maybe NitroJS could be *it*. If it threw away the sucky template format. Completely. No templates on the serverside. No serverside HTML generation. Pure HTML is the new template standard (see below).
  • URL routing should use the object hierarchy on the appserver as default. Explicit URL routing (static or using regexp) would have to be done explicitly.
  • for the presentation layer I want pure HTML+JS. The browser should be the only component responsible for rendering templates. The clientside part of the framework should make all calls to the server using REST/AJAX and providing JSON-formatted parameters. No GET or POST parameters. It should only accept JSON-formatted results. No HTML. Standard HTML is the only templating system needed. Page elements (DIV, SPAN, etc) should have an “id” as an identifier for serverside databinding. If a page has a tag/field with “id=xpto” then that tag/field should be filled with the contents of the “id” key returned from the server in a JSON string. A good starting point would be PURE, but without using “class” as the databinding identifier (“id” should be the standard).
  • I want the appserver to have features that Zope has had for years: I want acquisition (aka prototype-based programming, aka JS object-orientedness). I want a through-the-web management interface. I want ZClasses. I want automatic form generation for classes/objects and an automatic management (CRUD) interface for objects.

So, how’s that? It’s Xmas anyway, so I can ask for whatever I want. Gimme, gimme… Or I can start working on it… Who’s with me? I can be the Main Bitcher, Overall Architect and Project Manager.