Null Object Pattern

One of more dangerous patterns that I have seen is Null object pattern. Premise is simple enough: Instead of your function returning null (e.g. when it cannot find an item) it should return special empty object. This avoids null references exception if such object is accidentally used. With simple change to way how we return object we just got rid of crashes. What could go wrong?

Well, someone might implement new functionality a year down the road. Not knowing about this behavior he will check for null in some border line case. Since change is small, no one will do full testing (of course, in real world, any change triggers full retesting :)). His borderline behavior just went from well defined (check for null and take action) to pray that empty object does not get inserted into main program flow.

Exceptions are your friend. That kind of friend that will kick you in the arse when you do something wrong. Having empty object instead of null will indeed stop the crash. However, there is now empty object floating around. Programs are complex and this object is bound to get into wrong place. Best case scenario is that no data gets corrupted.

Null reference exceptions that you would get traditionally are probably among simplest exceptions that you can find in the wild. From stack trace you can see where object is null and just backtrack from there. And probability of data corruption is quite low since program crashed before actually doing anything with affected object. Even if something wrong got inside, crash is quite a clear signal that something is amiss.

Debugging any errors produced by this pattern is not a trivial task. You will probably only notice that something is wrong on data. And you will not notice that error immediately. No, it will be in database for days, weeks if not years until some TPS report exposes it to public. And then you need to find offending code. Talk about needle in haystack…

I view using this pattern as telling someone to kick you in the balls. Maybe there is good reason to take such action, maybe there are even some benefits. Nevertheless there will be some pain involved and one should better be sure that this is really action that is needed.

QText 3.20

QText screen

New version of QText has one feature that I planned for a while now.

Just right-click on any tab, select encrypt and chose your password. Upon first access to tab you will get password prompt and file will be decrypted and left open in order to be used. As soon as program is closed and taken to tray, file will be locked again. Other than password prompt, look and feel of encrypted files should be same as it was before.

For those that like three-letter abbreviations, 256-bit AES in CBC mode is name of the game. Security-wise it might not be a best choice since (in chosen implementation) it derives key and IV directly from password. Since that operation is very fast, unfortunately this also means that is very fast to mount brute-force attack. Of course, the longer password, the more resilient it will be. I wouldn’t save my nuclear-launch codes here, but everything else should be safe.

I always tried to keep data accessible to user even without QText installed. That was main reason driving decision to use text files and folder structure as storage mechanism instead of single file. Availability of user data is what also drove me to use OpenSSL encryption here. OpenSSL is available on virtually every platform. Because of same algorithm it is possible to manually decrypt each file if need arises:

openssl aes-256-cbc -d -in file.txt.aes256cbc -out file.txt -k "password"

I consider this a good trade.

As always, upgrade is available from within application or at these pages.

Choose Your Poison

When dealing with programs there are almost always multiple ways to write same thing. Rule of thumb is usually to write it in most readable way. And there people start disagreeing what exactly is readable. Let’s take simple condition:

if (object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == true) {
    ...
}

Both these statements do exactly same thing. Heck, they even get compiled to same code. However most programmers I have ever met prefer first one. It just makes intention clear in shorter form.

It’s negative cousin would be:

if (!object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == false) {
    ...
}

Again, both statements are same. But I can bet that they will do almost perfect split among programmers. Half of them will prefer concise form with other half preferring longer form. Reasons will vary. For some exclamation mark is too easy to omit when scanning code. For some longer form just sticks out for no good reason.

Personally I passionately hate negative statements and I will avoid them whenever I can. If I really need them I am in group that strongly believes that later form, while longer, is superior as readability goes. For me that is worth seven additional characters. Strangely enough, in positive cases, I omit true.

P.S. One more variation of negative case would be:

if (!(object.equals(obj1, obj2))) {
    ...
}

It might as well be in goldilocks zone. It gives a bit more visibility to exclamation mark by enclosing everything in another set of brackets. Of course, given statement long enough, it can look rather crowded.

Selecting a LDO Voltage Regulator

Illustration

I am in process of creating new USB board for my personal nefarious purposes and I needed nice 3.3V voltage regulator. Usually I just use LD1117DT33TR. It has decent maximum current, works up to 15V and it comes in nice DPAK package that helps to keep it cool. However, for this occasion, it was just too big. I wanted something smaller.

While simplest thing would be to pick one that would suit me in this project. However, I always like to spend a bit more time in order to get a chip that I can reuse in bunch of other projects. Here were things that I desired:

  • 3.3 V
  • at least 50 mA
  • SMD
  • LDO
  • easily available in Croatia
  • very simple
  • preferably cheap

First I searched on RS Croatia site for all LDO 3.3V regulators in SOT-23 package. Sorting them by price gave me few candidates. They were AP7313, TS9011SCX, TC1014, SP6201EM5 and MCP1700. All others that were cheap enough were variations of same basic devices. Quick search on DigiKey didn’t find TS9011SCX so it was automatically disqualified. High cost removed SP6201EM5. If I am searching for jelly bean component, I want to have one that is always available and very cheap.

Another odd-man out was TC1014. I haven’t had anything against it’s specifications. They were good enough and in some parts better than chips that stayed in competition. However, it had five leads. I wanted my final choice to be as simple as possible. That left two SOT-23-3 devices in race: AP7313 and MCP1700.

Both these devices satisfy all my needs. And then some. Both have short-circuit protection, thermal protection and both are stable with 1 μF ceramic (nice!) output capacitor. For most parameters where MCP1700 was slightly better they were close enough not to really matter. Great example would be quiescent current. While on first glance there is huge difference in favor of MCP1700 (40x) that only matters in case of extremely optimized battery-powered device. Since almost all devices I do revolve around computer, it is just parameter that I do not care about. For all jelly bean 5 to 3.3 V LDO purposes they are equivalent.

After spending some time going back and forth I decided to use MCP1700T-3302E/TT. Reason was stability. While both regulators work with ceramic capacitors, AP7313 requires output capacitor ESR to be 20 to 200 mΩ. This does cover wide range of ceramics, but for MCP1700 is even better. It’s output capacitor can have ESR anywhere from 0 to 2000 mΩ. That range covers pretty much all capacitor types that I would find on my shelf.

If something comes up where AP7313 would be great fit (e.g. no minimum load), I am fine with that also. You see, AP7313 comes in two different footprints. In case of AP7313-33SRG-7 footprint is same as one that MCP1700 uses. You can mix and match them based on cost and availability as much as your heart desires (just watch for those capacitors!). And that gives real lesson of this post: whenever you can try not to limit yourself to single supplier.

Mercurial on CentOS 6.2

For pure server tasks there is probably no better free distribution than CentOS. What is then more natural than use it as a Mercurial server?

I will assume that CentOS 6.2 is already installed (at least minimal) and DHCP (if used) is already set up. Simplest test would be connecting via SSH. If you can connect, you are ready.

First step would be to install our web server. There is no doubt (ok, there is some) that Apache is way to go here.

yum install httpd
service httpd start
chkconfig httpd on

After installation we need to adjust firewall and test out setup by pointing our browser to whichever address our server has (in my case that would be 192.168.56.101). When you get Apache test page, you can continue further. Until that time, fiddle with settings.

There is already a Mercurial package included within CentOS repository but it is rather old version (1.4). We will go with newest and greatest. At time of writing that would be Mercurial 2.2.2.

rpm -Uvh http://pkgs.repoforge.org/mercurial/mercurial-2.2.2-1.el6.rfx.i686.rpm

Now let’s create directory structure:

mkdir -p /srv/hg/cgi-bin
cp /usr/share/doc/mercurial-2.2.2/hgweb.cgi /srv/hg/cgi-bin/.

Next we need to edit /srv/hg/cgi-bin/hgweb.cgi. Find line that has config parameter and replace value with “/srv/hg/cgi-bin/hgweb.config”. Then create /srv/hg/cgi-bin/hgweb.config and write:

[collections]
/srv/hg/ = /srv/hg/

[web]
allow_push = *
push_ssl = false

Those settings will allow for HTTP-only operation where everybody (authorized) can push changes. For small networks this might be suitable, but you should probably be looking into at least enabling HTTPS. Guides for that can be found all around. You can find even (Ubuntu-specific) https guide on these pages so feel free to adjust and configure.

Last change will be to /etc/httpd/conf/httpd.conf. At the very bottom we will add following text:

NameVirtualHost *
<VirtualHost *>
    DocumentRoot /srv/hg/cgi-bin/
    ScriptAliasMatch (.*) /srv/hg/cgi-bin/hgweb.cgi/$1
    <Directory "/srv/hg/cgi-bin/">
        SetHandler cgi-script
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>
    ErrorLog /var/log/httpd/hg.log
    <Location />
        AuthType Basic
        AuthName "Mercurial"
        AuthUserFile  /srv/hg/.htpasswd
        Require valid-user
    </Location>
</VirtualHost>

Short restart later (another service httpd restart) you should be greeted with 403 forbidden.

Turns out that there are few more things to do. First one would be to create new user (testuser).

htpasswd -c /srv/hg/.htpasswd testuser
 New password:
 Re-type new password:

After that is sorted out, we need to adjust directory rights:

chown -R apache:apache /srv/hg/
chmod a+x /srv/hg/cgi-bin/hgweb.cgi

Last setup step would be to adjust SELinux security a bit. Easiest way would be to disable it completely (check /etc/sysconfig/selinux). Proper way would be to just load module which allows actions that we need. While you can troubleshoot this yourself, I have also prepared pre-compiled SELinux module (only httpd-mercurial.pp is really needed, other file is for reference). After unpacking, just execute:

semodule -i httpd-mercurial.pp

And that is it. Now you will be able to access your repositories at 192.168.56.101 (replace IP with yours) and do with them as you please.

P.S. To create repository all you need is to:

cd /srv/hg/
hg init TestRepo
chown -R apache:apache TestRepo