Saturday, June 14, 2014

Named arguments in C

When experimenting with some C99 features of C, I found a very cool trick to have named parameters, using a feature called designated initializers. The first time I read about designated initializers I must admit I found it to be pretty useless, but as I started testing it out, I ended up finding it very useful, since it can make code a lot more readable. Using it together with variadic macros, it was possible to have a very clean named parameter system.

Straight into the code, this is the technique:
typedef struct { int year; const wchar_t *name; } Foo_args; // parameters
void Foo_func(Foo_args args) {
	int x = args.year + 10; // use the argument
}
#define Foo(...) Foo_func((Foo_args){ __VA_ARGS__ })
And this is how you call the function:
Foo(.year = 2014, .name = L"Rodrigo");
The function calling is clear, and its implementation doesn’t add much noise to the code: I believe the price is payable and the result is worth.

Tuesday, May 13, 2014

Fixing .htaccess in Apache with Ubuntu 12

I have an ordinary Apache installation on an Ubuntu 12 OS, where the root webserver directory is ordinarily pointing to /var/www. I have many subdirectories within it, and I’d like to have one of these subdirectories using clean URLs, specifically becaused I was testing some RESTful API stuff. However, I’ve struggled a bit to make Apache recognize my .htaccess file.

So, after some minor stress, here it is the quick step-by-step guide of what I did, without further explanations:
sudo vim /etc/apache2/sites-available/default
Within the Directory /var/www directive, change AllowOverride None by AllowOverride All. Then run these two commands:
sudo a2enmod rewrite
sudo service apache2 restart
And all of sudden it started working.

Friday, March 28, 2014

A simple alternative to C++ exceptions

I’ve been doing a lot of C++11 research and coding ultimately, and I’m still upset with the C++ exceptions. When reading the concepts, it seems to be a reasonably good alternative to simply return a boolean, but as you try to stuff it in your code, you begin to feel like manipulating a stressed hedgehog. And it’s very frustrating, since you have to stop thinking about your code – what really matters –, to think about the implications of the code you are writing upon the code itself.

Usually, my needs are really simple, I just need an extended way to report a success or a failure from a function. I never wrote something that really needed to tackle differents kinds of errors: it’s just success, or failure with a reason, which usually popped in an alert message box.

After quitting the exceptions, when trying to solve this problem, my first move was to use an extra string pointer as the last parameter to hold eventual error messages. It goes like this:
bool Func(int p1, int p2, wstring *pErr=nullptr) {
	if(false) {
		if(pErr) *pErr = L"Error message.";
		return false;
	}
	if(pErr) *pErr = L""; // all good
	return true;
}

bool Second(float nn, wstring *pErr=nullptr) {
	if(!Func(42, 1337, pErr)) { // will return error message from inner function
		return false;
	} else if(false) {
		if(pErr) *pErr = L"Another error.";
		return false;
	}
	if(pErr) *pErr = L""; // all good
	return true;
}

{
	wstring err;
	if(!Func(42, 1337, &err))
		scream(err.c_str());
}
There is no problem with this approach, and I used it for quite some time. It is clear, and one would have no doubts about what is going on. It is, however a bit cumbersome to write all those pErr checks. So at some point I started considering something else.

My second approach was to use a standard pair as the return type to the function. Something like this:
pair<bool, wstring> Func() {
	if(false)
		return make_pair(false, L"Error description message.");
	return make_pair(true, L"");
}

{
	pair<bool, wstring> ret = Func();
	if(!ret.first)
		scream(ret.second.c_str());
}
I never really used this. It doesn’t look clear enough, and the declaration of the pair variable, just to hold the return value, doesn’t amuse me.

Then I start thinking about writing a “bool on steroids” class, specifically overloading the operator bool, so there would be no need to declare a variable just to hold the result value of the invoked function. This is the class:
#include <string>

class Failed {
public:
	Failed(bool allGood)                   : _hasFailed(!allGood) { }
	explicit Failed(std::wstring reason)   : _hasFailed(true), _reason(reason) { }
	explicit Failed(const wchar_t *reason) : _hasFailed(true), _reason(reason) { }
	virtual ~Failed()                      { }
	operator bool() const         { return _hasFailed; }
	const wchar_t* reason() const { return _reason.c_str(); }
private:
	bool _hasFailed;
	std::wstring _reason;
};
And this is the usage:
Failed Func() {
	if(false)
		return Failed(L"This function failed.");
	return true;
}

Failed Second() {
	if(Failed f = Func()) { // if Func() returned false
		return f; // return from inner function
	} else if(false) {
		return Failed(L"Another error message.");
	}
	return true;
}

{
	if(Failed f = Second())
		scream(f.reason());
}
This approach looks a lot elegant to me. It’s clean, allows the chaining of error messages, and it even allows the inheriting of the Failed class to add more specific error data – although I never really needed this.

The only thing which makes me uncomfortable with this class is the _hasFailed member, which holds a reversed boolean value of the object meaning: if there’s a success, it’s false; if there’s a failure, it’s true. I implemented it this way so that I could use a declaration of the class within an if statement, with no need to declare a variable just to hold the result, as I did on the previous example when I returned a standard pair. Also, it explains why I chose the name “Failed” instead of something like “BigBool”: to explicit the idea of a failure being handled by the if.

Other than that, I consider it a neat approach, and that’s the best solution I could come up with so far.

Saturday, February 15, 2014

Queen 2011 remasters: horrible

As an audophile, I care a lot about my music collection. Some albums do have multiple pressings, with new remastered versions of the same old material. These remasters rarely surpass the originals, they tend to be overcompressed due to the infamous loudness wars, but I always seek to hear them, waiting for a miracle.

Right now I’m listening to the Queen 2011 remasters, which sound all really bad to my ears. I’ve read somewhere that Bob Ludwig was responsible for this work, but it’s hard to believe that such a great professional have done such a shitty job. Some songs – particularly the heavier ones – have so much compression that distortion is openly audible. The Jazz album is the worst one so far, with burnt peaks on all tracks, a mess of noise.

The Sheer Heart Attack song, from News of the World album, is a full block of deafening noise, that gave me a headache before the second minute ended, and I had to skip it. The same for the heavy parts of Brighton Rock and Stone Cold Crazy, from Sheer Heart Attack album. Basically, the songs are ruined, sounding really harsh, overcompressed on every single opportunity.

Label managers of today are not only stupid, they are deaf too. When I see things like this, I only can hope that digital music distribution kills this industry as soon as possible, as it is already happening. With the home studios and the internet, we don’t need their greed anymore.

Wednesday, January 29, 2014

JavaScript anonymous closures

Today I was going to write about my fruitful experiments in JavaScript using anonymous closures, scope and namespacing in general. But I stumbled across two articles that are so good, that I just felt the need to publish the links to both, because they explain everything I was about to write in great detail:
As of today, 3+ years old articles, which are still contemporary and relevant to JavaScript development. Highly recommended reading.

Thursday, January 9, 2014

Logitech, please bring back the wired Trackman Wheel

About 2 years ago I was suffering from some wrist pain, due to countless hours of computer work with an ordinary mouse. I started searching for some device to relieve the pain, and after test several gadgets, I came across the Logitech Trackman Wheel. It’s a trackball which sphere is moved with the thumb, leaving the whole hand resting on the desk. And it’s absolutely great, precise, comfortable, I could use that thing for hours without any signs of tiring.

This week, however, the left click just started acting numb, unresponsive, and I found a video teaching a way that could possibly fix it. After three days, the problem seemed to be unfixable, so I decided to buy another unit of this wonderful thing. But to my surprise, I found out the Logitech discontinued the Trackman Wheel, in favor of a wireless version called M570, which like any laggy wireless device, relies on batteries, which require you to figure out when they start dying, so you can buy more batteries to replace the old ones, if you don’t have them dying in the middle of an online game, for example, case when you’d be screwed. Oh, and also it has an annoying switch to turn on and off, so that’s another thing you have to remember to do. The Trackman is supposed to stay fixed on the desk, so why the hell do you need a wireless version of it?

I’m not the only one who wants the wired Trackman Wheel back, there’s even a group on Facebook with people discussing this. Unfortunately, Logitech didn’t reply the user complains, and so far there’s no hope to have a wired version of our beloved Trackman Wheel.

I could not find any unit to buy, not even on eBay. By now, I’m desperately trying to find a way to fix my old and good Trackman Wheel, to use it for as long as I can. And to Logitech, for blindly joining this wireless bandwagon, I just want to leave a sincere fuck you, Logitech.

Update, Jan 11:
This morning I found a skillful electrician who managed to swap the bad left click component with the middle click one, which was working fine. Now I don’t have a middle click anymore, but at least my beloved Trackman Wheel is usable again.

Tuesday, December 17, 2013

Creating project templates for Visual Studio 2013

There are a couple of project settings that I set for every native C++ Win32 project I want to start, basically, more aggressive optimizations for the release build.

Right now, messing around with my brand new Visual Studio 2013 – which I’m appreciating so far –, I discovered how to create a template project with all the settings I need, including subfolders and files. I found this article which explains the process for an ASP.NET MVC project, but the steps are the same for a C++ one.

The templates are exported as ordinary ZIP files, and importing existing ones is trivial, you just need to copy this ZIP file into the base directory. On my computer, this is the full path for the custom user templates:
C:\Users\Rodrigo\Documents\Visual Studio 2013\Templates\ProjectTemplates
In addition to the project settings, I also put in the template a subdirectory called “src”, my very basic main.cpp file, which contains my wWinMain entry point. It seems that I’ll never have to write it again.