Original, Shorts

Powershell closures

As a follow up to the previous article, I needed to warn you (and me) about powershell closures. They didn’t work as i expected

$Foo = 1
Write-Host "I expect Foo to be 1: " $Foo

function New-Closure {
    param([Scriptblock] $Expression, $Foo = 2) 
    & $Expression

New-Closure -Expression {
    Write-Host "I expected Foo to be 1, but was 2: " $Foo

New-Closure -Expression {
    Write-Host "I expected Foo to be 1, and it is: " $Foo

The confusion point for me was that $Foo can be changed by the invoker, unless we add the .GetNewClosure().

As in the previous article the parameter name $ResourceGroupName is very common, it’s best to always use the .GetNewClosure() on the ScriptBlock

Original, Shorts

Execute an arbitrary piece of code with a temporary file uploaded to azure

A short one today.

My use case is to run a Set-AzureRmVMCustomScriptExtension command. For it to work i need the script to be somewhere accessible by the VM.

Nothing to fancy. Might be useful for someone (or a future version of me). It creates a temp container, uploads the file, invokes the code passing in the URI, and whatever happens the container will be deleted. Assumes a connection to azure and an already existing storage account.

Just to highlight an interesting point

“temp-container-” + (-join ((97..122) | Get-Random -Count 5 | % {[char]$_}))

Initially i just had “temp-container” but when running 2 times in a row I got an error saying that the container could not be created as it was being deleted. So I found a way to generate random letters and now it creates an “unique” container each time.

Longs, Original

How much logic is too much logic?

Today there was a small argument about constructors and how slim should they be.

In this post I will attempt to explain my position on it.

On a general note, we all agree that constructors should not do much. Nevertheless I affirm that it is acceptable and even useful in some cases, to have logic in them, given that some rules are respected.

In the remainder of this post I will refer to the logic in the constructors as simply “logic” but this can be:

  • Straightforward operations
  • Complex logic, or even
  • IO access

The main contention point is that constructors should not have operations that may throw. First I will review the arguments against it, and then give some arguments for it.

There were 4 lines of argument against having “logic” inside a constructor body

  1. Hard to trace exceptions/memory leaks
  2. Single responsibility
  3. Principle of least astonishment (POLA)
  4. Dependency injection for decoupling/testing purposes

On the point one, this is simply not true in most cases

The hard to trace exceptions only exist in cases that you don’t instantiate the class yourself and don’t have logging in place to see the stack trace. It’s really not applicable

The memory leaks traces back to c++ that can allocate memory for an object and never free it if there is an unhandled exception. In .net this is not applicable either because the language is garbage collected.

If there is no destructor and no object that needs to be disposed, this is no reason for not having logic in the constructor

On the point two, the single responsibility is arguable

This is a reasonable principle, the contention point being what is the responsibility of the constructor.

If the constructor is doing side effects or mutating other objects, this is clearly bad but if the “logic” is about getting the object into a valid state i would argue that it is valid logic to be inside the constructor

On the third point, POLA, let’s see what could be astonishing

If you give an object a set of invalid parameters, should you be astonished that it throws an exception?

If you give an object an connectionstring, should you be astonished that it goes to the database?

If the object cannot get into a valid state, should you be astonished that it cannot be instantiated?

It is a good principle, but i don’t think any of the above cases is astonishing

On the fourth point, inversion of control, I agree on all cases

If you want your object to be testable, it should not instantiate any other object directly unless the two objects should only be tested together

If you want your object to be testable, it should use any static member directly

If you violate these principles, unit testing is impossible. Your tests will include more than your object

My main argument is that i believe that a constructor should only allow an object to get into a valid state. I believe that this is reasonable and is not on contention.

The constructor’s job is to bring the object into a usable state. There are basically two ways you can do this:

  1. Two-stage construction. The constructor merely brings the object into a state in which it refuses to do any work. There’s an additional function that does the actual initialization.
  2. One-stage construction, where the object is fully initialized and usable after construction.

I don’t think the two stage method is a good approach. Every method should enforce that it is not ran if the object is not valid, and there is a good chance the Init method wont be called if the class is to be reused by many people

I’m in favour of the one-stage construction.

There is also two ways you can do this, if you want to keep your code DRY

  1. Have a method somewhere that has your initialization logic

The best place in my opinion is a static Create method along side the constructor

2. Have your logic inside the constructor

I have used both approaches and believe that both are valid. I don’t have a strong opinion about which one should be used.

What do you think?

Shares, Videos

Dr. David Berlinski: The Devil’s Delusion: Atheism and Its Scientific Pretensions

I saw yesterday this video and found it very interesting.

Here are some excerpts from the letter mentioned in the beginning from Galileo Galilei to Benedetto Castelli

…it seems to me very prudent of her to propose and of you to concede and to agree that the Holy Scripture can never lie or err, and that its declarations are absolutely and inviolably true. I should have added only that, through the Scripture cannot err, nevertheless some of its interpreters and expositors can sometimes err in various ways.

I should believe that the authority of the Holy Write has merely the aim of persuading men of those article and propositions which are necessary for their salvation and surpass all human reason, and so could not become credible through some other science or any other means except the mouth of the Holy Spirit itself. However, I do not think it necessary to believe that the same God who has furnished us with senses, language, and intellect would want to bypass their use and give us by other means the information we can obtain with them.

Longs, Original

The Hidden Forces that Shape our Decisions

I recently watched this talk from the GOTO conferences and really enjoyed it.

Here is a summary and my general opinion on it.

The speaker is Fabio Pereira, author of Digital Nudge. He says he is a Digital Behavioural Economist — a digital nudger.

My goal is to help people make better decisions while designing and living in the digital world. — digitalnudge.org

He starts by raising the audience’s awareness to the vast number of choices we make each day and how many of those choices are nowadays influenced by the digital services we use.

When we do a Google search to aid our decision making does the Google algorithm influence our choices?

Fabio then goes into a series of examples of cognitive biases.

The one that stood out the most for me was the status quo bias. The tendency to like things to stay relatively the same. We are lazy. We keep the default choices. As an example, countries where you have to opt out of being an organ donor have a higher percentage of the population registered as donors.

Our actions aren’t always fully intentional. This can be exploited to coerce us to do things we would not do if we really thought about it.

There is a great book that Fabio references in the talk in which a theory of mind is presented. This theory is that we have two brains or in the book’s nomenclature, two systems.

  • System 1 operates automatically and quickly, with little or no effort and no sense of voluntary control.
  • System 2 allocates attention to the effortful mental activities that demand it, including complex computations. The operations of System 2 are often associated with the subjective experience of agency, choice, and concentration.

I haven’t finished this book but I believe it to be a great model of our brains and it shines some light about how we make our choices.

When you’re scrolling through your Facebook feed is your System 2 engaged or just the System 1?

There is an obvious need for the general public to know these things. Once you’re aware of them you are not so easily manipulated. There is a new type of intelligence needed to navigate the digital space in this century. Digital intelligence. We need to improve our digital IQ.

Fabio also makes the distinction between persuasion and coercion before going into the ethics of digital services.

  • Persuasion — getting people to do things they want or need to do
  • Coercion — getting people to do things they do not want or do not need to do

He says that we need to help people to do things that they want and need to do and because of that he started the movement #DigitalNudges4Good.

Up to this point I agreed with him almost absolutely. I only wanted to make two points:

  1. It’s sometimes hard to know what people need to do. We are limited in our knowledge and cannot always predict the full outcome of our actions.
  2. Sometimes people want to do things that are not good for them. They might think so but they can be wrong. There is a need to discuss here who decides what is good.

After a couple of minutes the talk ended and it was very good overall. Then something happened that blew my mind.

I seldom listen to the QA session after the talks but this time I kept watching. There was a question. Never mind the question and answer, it’s all about the introduction:

What I believe in, and it’s always a belief…we believe in something. There is no such thing as real truth because we don’t even know if we are in Berlin, if this is reality.

I mean.. it’s just nonsense…

There is no such thing as real truth? Is that really true or not? Let’s think about this statement. There is only two possibilities:

  • If it is true, then there is no such thing as real truth and so the statement is false
  • If it is false, then there is such thing as real truth and so the statement is false

Either way it’s false. Real truth exists. I have three questions:

  1. Where did he get the idea that is no such thing as real truth? People that promote the idea that truth does not exist are either not very intelligent, didn’t really think about it or are actively promoting a lie. The lie that all is relative.
  2. Why did he believe it? I mean… he seems to be a smart dude. Much more eloquent than me…
  3. What are the consequences of believing this lie?

I cannot answer to 1 and can only speculate about 2, but I can say something about 3.

If it’s all relative then enabling people to do what they want to do — persuasion in his definition — is always a good thing. At least to the one being persuaded. If his perception of reality is all that is, then persuading him to do what he wants he will be the best thing to do.
In another way it does not make any sense to believe that everything is relative and then try to convince everyone to be ethical on the services they provide online. Why should I not use dark patterns to have more conversions on my service? Is it true that doing so is bad? Says who?

I want to write about truth — why not everything is relative, how to find what’s true and what are the consequences of believing that there is no such thing as real truth. Maybe in Portuguese next time…

Original, Shorts

Privacy! The next big thing!

Is well known that companies know more about us than we would like them to know. Does this mean that we should quit any contact with the technology world and go live in a cave?

Stuart Langridge says no. There are ways through which our data may be collected and information is extracted from the aggregated properties of everyone’s data, but enough noise is introduce in each individual’s data so that it cannot be used reliably to target a single user.

We should demand this from the products we use. This could be the next big thing!

Longs, Original

Quitting a git GUI habit

I’ve been a user of source tree but it has let me down many times (crashes, high memory usage).

I’ve recognized that i really don’t know that much about git. I should learn at least the commands I use the most.

I’m a windows user so posh-git is a must have. There are great docs for git but they can be a bit overwhelming and have a lot of detail that is not needed 90% of the time. So, here it is, my 7 item git jump-start list:

  1. git checkout <branch>

The most basic command for switching branches. You can use -f to throw away any local changes

2. git fetch

Used to update the remote status. Useful to know if i need to pull. Use -p to remove any remote-tracking references that no longer exist on the remote

3. git pull

Pulls latest commits from origin. Use -r to rebase changes that are not yet pushed

4. git add

Adds changes to the staging area. Use -a to add all changes.

5. git commit -m “<message>”

Commits currently staged changes. Use -a to stage all changes before committing.

6. git push

Push currently committed changed to origin.

7. other stuff

I’m already cheating about the 7 items but now I’m getting into less used commands. git stash, git merge, git commit with amend, git push with force are all great tools to know about.

I cannot get my head around git diff. I still use GUI tools to handle conflicts and to review changes before committing.

That’s it. This list should be enough to keep me from using a GUI to interact with git most of the time.

Original, Shorts

Show up, kick ass, go home

I love programming. I really do! But programming is not my life, it’s just my job.

Since I’ve married and had kids this has become even more evident. There are things I have to do and that I also want to do besides thinking about my job.

I had been thinking about this a couple of days ago but today I read an article that really summed up my thoughts.

A couple of highlights:

“I opted in to this mindset (show up, kick ass, go home) largely in order to protect my own sanity. If I don’t set clear boundaries as to when it’s OK to think about work problems, I’ll think about them all the time,”

“For a puzzle-hungry brain like mine, programming is so full of not-yet-solved problems that a mind like mine can find entertainment and solutions to their hearts content and still not feel like they’ve truly accomplished anything”

Thanks Matthew Jones for being so articulate!

Original, Shorts

Pequeno comentário ao filme Hacksaw Ridge

Vi recentemente o filme o herói de Hacksaw Ridge. É um bom filme. Dos que gostei mais nos últimos tempos. Gostei principalmente por ser baseado numa história verídica.

Capa do filme

​A frase que mais me marcou foi a que o herói dizia de cada vez que ia buscar feridos ao campo de batalha.

Just help me get one more Lord.

A guerra com os japoneses era — discutivelmente — justa porque defendia um estado e os seus valores contra agressores estrangeiros. O herói, Desmond, apenas queria salvar a vida dos seus semelhantes quer amigos quer inimigos ao mesmo tempo que participava na guerra que acreditava ser justa.

Se cada homem tem uma alma eterna, a sua vida tem mais valor do que qualquer estado ou instituição existente. Os estados e instituições vão todos passar eventualmente. A alma vai existir eternamente. Eu acredito nisto. Assim sendo, também quero entrar na guerra para salvar a alma dos homens do inferno. Quero tal como o Desmond, dizer a cada dia:

Just help me get one more Lord.

Longs, Original

Developer evolution

One of the great things of staying on the same job – and on the same project – for a long time is that once in a while you get to see code you wrote years ago. Yesterday was one of those days. I had the opportunity to see how much my coding skills had evolved.

I was confronted with a performance issue from a piece of code I wrote 5 years ago. After a couple of hours I and a colleague pinpointed the bottleneck and rewrote the problematic code. The code ran 6–8x faster.

I want to make 3 points from this:

  • Don’t optimize prematurely. The code was in production for 5 years and was good enough. In that time I could improve my understanding of the whole system, a crucial skill to make good design decisions.
  • Challenge yourself. The bottleneck was quite obvious once I saw it. 5 years ago I didn’t have the maturity to question my own code. This could have been avoided with tools like pair programming or code reviews but it’s always a good thing to take a critical look at your work before checking in
  • Measure. Sometimes the problematic code is not that obvious. There are great tools that help you to measure the performance of your code. Learn to use them.

I want to thank the developer – or team – behind CodeTrack. It’s a great tool and on top of that completely free! If you work in .net it’s a must have.