Exceptions again. I thought about them again after posting earlier about how pointless they are. I found some cases where they might be useful, but then I changed my mind.
For instance, I know it's truly elegant to write a = b + c * d - x++ with overloaded operators and just catch the exception instead of checking the result of each operation, but what if(a.has_error()) do_stuff_to(a.get_error()), something like aggresively_spit_message(a.get_error()->
get_human_readable_text_including_error_ \
type_and_operand_misvalue_and_any_releva \
nt_environment_problems())?
And do whatever you like within the operators regarding operating on data with errors, just pass on the error.
I also know that even if you don't (can't) overload operators some methods must return useable objects, especially if you have immutable objects. Then either have mutable objects and pass them by reference, or make the error part of the object just as above. Duh.
Tuesday, October 16, 2007
Monday, October 15, 2007
fry
Today I am going to talk about frying electronics. According to arcane lore, all electronics function by means of a mysterious substance called the Magic Smoke. It is inserted into the components when they are manufactured, through a highly secret alchemic process. Whenever the magic smoke is released - for instance through subjecting the component to an electrical current many times the one specified for normal functioning - it ceases to function. This is sometimes accompanied by strong luminous or acoustic events (flash-bang). Other times, depending on the energy involved, it also results in flying sparks and shrapnel: "Timmy, put down that transistor! You might poke somebody's eye out!"
Although sometimes embarassing, especially when frying something worth a lot of money, accidentally killing electronic components is seen by engineers and amateur enthusiasts alike as sort of an initiation rite.
Frying electronics can be the result of numerous mistakes, such as:
There are also more interesting ways of frying electronics. We had some "Digital Computers" labs where we would design some simple stuff involving digital logic and stuff it into an FPGA and test it. Worth mentioning is the famous "Automatic coke dispenser" that was simulated using switches for dropping coins and LEDs* for releasing bottles as well as for internal diagnostics. *) Under the right conditions, any diode can emit light in the form of thermal radiation. Most can only do it once.
The coke dispenser never worked, partly because it was very easy to do the equations wrong, partly because the state machine was hand-designed and hand optimized instead of being written in some behavioural language, and partly because there was no switch debouncing. But, it taught us about whistling bits into an FPGA and reminded us how to hand-design stuff.
Another interesting one was the "robot ant" that navigated through a maze. It had VGA output but that module was already written so it was very cool (dude! video output dude! on the fucking monitor dude!) but not that challenging. The ant always looked like it had a blind desire to mate with the walls, but hey, it was all done in hardwarde. Sort of.
Years passed and one of my friends had to go through this lab. He asked me: is there some way you can fry an FPGA by misconfiguring it? I immediately said no, thinking of the usual mistakes one might do when generating the configuration bitstream, the same mistakes one would do when doing classic C programming for instance. After all, an FPGA is a very, very expensive thing to fry and you wouldn't want to be able to do that in software. Not easily at least. And the guy was sincerely concerned and I had to calm him down. And then I thought, well, if you wanted to fry it, I guess you could very well do that. (Don't!) You could for example take the clock and use an internal PLL to multiply it 6, 7 or even 10 times, maybe even way beyond what the chip is specified to properly function at. Then you would clock all the possible flip-flops with that, and tie all the combinatorial logic to it for good measure. That would surely overheat the chip in no time. If you're lucky, you might even blow up the power supply. If you're really lucky, the power supply might think you're short-circuiting it and shut down, preventing you from frying anything. Anyway, don't do such stuff.
Then (read hack a day!) I learned of a design that can really fry itself by software. It's a brilliant design actually, if proper protection is added. But it's just for proof of concept. Say you want to control a switching power supply by software. Need I say more? :) There's no greater opportunity for self-frying than this. This said, I would never trust software to keep me alive. I don't really know why we allow so many bugs to exist. I mean, when you design something physical, errors can creep up, but usually you do all the calculations and show that the stuff is going to function as planned. Not with software. Nobody does state diagrams and flowcharts anymore. In high school, we used to laugh when the teacher was trying to push flowcharts onto us. "What? Flowcharts?! That fucking looks like it's from an old sixties manual, I want to write some code!". Well. I admit it, I myself hate both flowcharts, Petri nets and proving algorithm corectness. Hell.
Although sometimes embarassing, especially when frying something worth a lot of money, accidentally killing electronic components is seen by engineers and amateur enthusiasts alike as sort of an initiation rite.
Frying electronics can be the result of numerous mistakes, such as:
- applying a voltage of incorrect polarity or magnitude - this results in internal breakdown or excessive conduction, which allows large currents to flow. Large currents times some voltage equals large Joule dissipation equals melting, and sometimes pressure increase = bang!
- allowing too great a current by wrong selection of component values - see above
- using a small resistor instead of a larger one (ohmically or mechanically) - ouch, it burned my fingers! Also see above.
- in particular, short-circuiting something that can deliver a large current does indeed that, sometimes with unpleasant results.
- electrolytic capacitor overvoltage - fizz, bang
- screwdriver across electrolytic capacitor - bang, sparks, screwdriver welded to terminals, capacitor internally overheated and mechanically stressed - bad
- diode across mains - boom, blown fuse (trust me and don't try)
- integrated circuit inserted backwards in socket - what students do in the electronics lab in the Bucharest Polytechnic to confuse their teacher - "Teacher, the circuit is not functioning, come take a look, I guess we wired up the thing wrong! [.......] So it's defective? Well, then, could you just let us off?" - the sockets are hidden on the back of the board and the traces and resistors are on the top side, for some arguable reasons like clarity and "don't touch those ICs, we don't have many more replacements! You don't need to see how those sockets work! Google it or something." -- doesn't work :)
- electrostatic discharge - ellusive, nasty and sneaky.
There are also more interesting ways of frying electronics. We had some "Digital Computers" labs where we would design some simple stuff involving digital logic and stuff it into an FPGA and test it. Worth mentioning is the famous "Automatic coke dispenser" that was simulated using switches for dropping coins and LEDs* for releasing bottles as well as for internal diagnostics. *) Under the right conditions, any diode can emit light in the form of thermal radiation. Most can only do it once.
The coke dispenser never worked, partly because it was very easy to do the equations wrong, partly because the state machine was hand-designed and hand optimized instead of being written in some behavioural language, and partly because there was no switch debouncing. But, it taught us about whistling bits into an FPGA and reminded us how to hand-design stuff.
Another interesting one was the "robot ant" that navigated through a maze. It had VGA output but that module was already written so it was very cool (dude! video output dude! on the fucking monitor dude!) but not that challenging. The ant always looked like it had a blind desire to mate with the walls, but hey, it was all done in hardwarde. Sort of.
Years passed and one of my friends had to go through this lab. He asked me: is there some way you can fry an FPGA by misconfiguring it? I immediately said no, thinking of the usual mistakes one might do when generating the configuration bitstream, the same mistakes one would do when doing classic C programming for instance. After all, an FPGA is a very, very expensive thing to fry and you wouldn't want to be able to do that in software. Not easily at least. And the guy was sincerely concerned and I had to calm him down. And then I thought, well, if you wanted to fry it, I guess you could very well do that. (Don't!) You could for example take the clock and use an internal PLL to multiply it 6, 7 or even 10 times, maybe even way beyond what the chip is specified to properly function at. Then you would clock all the possible flip-flops with that, and tie all the combinatorial logic to it for good measure. That would surely overheat the chip in no time. If you're lucky, you might even blow up the power supply. If you're really lucky, the power supply might think you're short-circuiting it and shut down, preventing you from frying anything. Anyway, don't do such stuff.
Then (read hack a day!) I learned of a design that can really fry itself by software. It's a brilliant design actually, if proper protection is added. But it's just for proof of concept. Say you want to control a switching power supply by software. Need I say more? :) There's no greater opportunity for self-frying than this. This said, I would never trust software to keep me alive. I don't really know why we allow so many bugs to exist. I mean, when you design something physical, errors can creep up, but usually you do all the calculations and show that the stuff is going to function as planned. Not with software. Nobody does state diagrams and flowcharts anymore. In high school, we used to laugh when the teacher was trying to push flowcharts onto us. "What? Flowcharts?! That fucking looks like it's from an old sixties manual, I want to write some code!". Well. I admit it, I myself hate both flowcharts, Petri nets and proving algorithm corectness. Hell.
Sunday, October 14, 2007
fuck i18n
sau de ce suge wikipedia în româneşte.
Pentru că, evident, sunt mult mai puţini oameni care scriu în porcăria de wichipedie românească decât în aia englezească (cu adevărat internaţională).
De exemplu, vreau să caut cum se zice în iengleză la a restitui ceva în natură, pentru că-s prost şi nu ştiu. Sau cum se traduce răspundere juridică, că poate-i un termen special, ceva. Mă, n-ar fi fost injust să fie nişte pagini dacă nu cu titlul ăsta (caz în care clicăiam linkul spre varianta internaţională), măcar să fie dracului menţionate pă undeva. Nu găseşti.
Romanian Wikipedia is a waste of resources and sucks by lacking lots of articles and it will never be able to get them (just as many of its other 'international' variants suck), fuck 'internationalization', the only international language is English.
Pentru că, evident, sunt mult mai puţini oameni care scriu în porcăria de wichipedie românească decât în aia englezească (cu adevărat internaţională).
De exemplu, vreau să caut cum se zice în iengleză la a restitui ceva în natură, pentru că-s prost şi nu ştiu. Sau cum se traduce răspundere juridică, că poate-i un termen special, ceva. Mă, n-ar fi fost injust să fie nişte pagini dacă nu cu titlul ăsta (caz în care clicăiam linkul spre varianta internaţională), măcar să fie dracului menţionate pă undeva. Nu găseşti.
Romanian Wikipedia is a waste of resources and sucks by lacking lots of articles and it will never be able to get them (just as many of its other 'international' variants suck), fuck 'internationalization', the only international language is English.
Saturday, October 13, 2007
titan
This should be part of the 'press' series. I saw an article about some astronomers discovering there's rain on Titan. Of course, it's not raining water but liquid methane, which is named an 'explosive gas'. This reminded of some show they used to air on Discovery about the moons of the Solar System. They were saying that, if oxygen were present on Titan, and one were to light a match, the whole moon would go up in flames. They were showing an expanding ring of fire that eventually circles the whole orange sphere leaving it black behind. Well, I find that very wrong on many levels. But first of all, methane is not explosive alone, it is explosive when mixed with oxygen, so don't call it that. On Earth it's an explosive gas under normal conditions, true, but not everywhere. Both sources recognize that, but the first still calls it explosive. Second, the whole idea of the moon going up in flames is pointless, because (a) there is no oxygen there and (b) if there was, it would have ignited with the methane from stuff like meteorites. Why ask oneself 'What if there was O_2 on Titan?' if that's not the case? Just for the trivially exciting fire ring. What if suddenly there was a lot of cianide in the air on Earth? We would all be dead, instantly, you could see all the people fall. Cool. Equally pointless.
Wednesday, October 10, 2007
sound
There are more or less frequent discussions of bad science in movies, games etc. Damn, this computer is slower than my typing, much slower. It's much slower even than the eBox I have at home, from which I've once blogged. It's so slow I can't be bothered to look up the link to that certain post.
Anyway, bullets have low momentum and can't launch a dude in the air, lasers travel at light speed which is for all practical purposes infinite*, and sound can't travel through empty space. Neither can laser light scatter off empty space, so the beams should be invisible except where they hit something. It's light, not projectiles.
*). compared to practical lengths for spaceships and human eye response time.
So people like me praise old, well thought-out movies like 2001: A Space Odyssey, where there was no sound in space, no gravity on space ships et cetera. New movies on the other hand feature low-budget crappy CGI, all sorts of glowing beams, explosion sounds synced with space stuff blowing up, and Earth-like artificial gravity everywhere. Then I thought. Dude, you can hear the sound from a blast in space, because debree would be hitting your vehicle. But I'm pretty sure it would sound very different from fire crackers.
Anyway, bullets have low momentum and can't launch a dude in the air, lasers travel at light speed which is for all practical purposes infinite*, and sound can't travel through empty space. Neither can laser light scatter off empty space, so the beams should be invisible except where they hit something. It's light, not projectiles.
*). compared to practical lengths for spaceships and human eye response time.
So people like me praise old, well thought-out movies like 2001: A Space Odyssey, where there was no sound in space, no gravity on space ships et cetera. New movies on the other hand feature low-budget crappy CGI, all sorts of glowing beams, explosion sounds synced with space stuff blowing up, and Earth-like artificial gravity everywhere. Then I thought. Dude, you can hear the sound from a blast in space, because debree would be hitting your vehicle. But I'm pretty sure it would sound very different from fire crackers.
anti-patterns
Time to relax (slow down brain clock while browsing Wikipedia articles on simple ubiquitous stuff just to see if something trivially interesting pops up).
Of course, this also leads to reading articles of a more specialized nature.
One of these would be the article on anti-patterns. I find the 'Reinventing the square wheel' list entry the funniest :D
Note the smileycon used as sentence-terminating punctuation mark.
Anti-patterns are called so because in many (most?) cases they're bad, m'kay?
Not always.
1. Come From and Go To
(listed as 'Spagetti Code')
goto is useful, and is indispensable if programming in assembly language. Few processors support 'if' and 'for' and 'while' natively, most use jumps (gotos) to emulate them.
2. Busy Waiting
(spinning in a loop waiting for something to happen/finish instead of doing something else and waiting for a signal)
They taught this with great passion and emphasis in Operating Systems class. No busy waiting, use wait functions that yield control to another thread, halt the processor to sleep if it has nothing to do. Which is obviously reasonable. You don't want a task to spin doing nothing, you want it to sleep and let another one run. If none has anything useful to do, halt the processor to save power. That can't be anything but good, right?
Wrong. Turning on the processor to do useful stuff and then off while waiting for more stuff to do trashes the supply voltage by drawing large current spikes. In an improperly designed (or cheap) system, this can induce audible noises in the speakers, audible noises from power supply coils (hear them when scrolling text?) and electrical noise leading to poor measurement precision in embedded data acquisition systems. That's why all my microntrollers spin and never sleep. Many don't use interrupts at all and poll all peripherals except timing-critical ones. Waste of power? At some tens of milliwatts, from the mains and not from batteries, I couldn't be made to care. I own and control all tasks, I know how long they (should) take, I schedule them, I own all time and silicon Mwahaha, I spend 4 hours debugging. I rule :)
Also, spinlocks and atomic operations are good, m'kay. And well-documented.
3. Raising, catching and ignoring exceptions
(and all sorts of other problems)
Blah! What's wrong with just checking return values?
Why do we need exceptions? Certainly not because of abstraction and object-orientation.
If I ask you to please go take a shit, you can do it and reply with "Done." (return 0, or the more oxymoronic ERR_OK), or you can not do it and reply with "All portable toilets in range have their doors locked." (return ERR_NO_TOILET), or "No." (return ERR_GENERIC). I can then choose to check or ignore your return value, or just check to see if it's null. You can even return a pointer to an error object (supposing that the method halts on the first error encountered, use a list otherwise), though you would need some sort of RTTI to implement various types of errors just as you traditionally do with typed exceptions. But that can be messy, so you could just use one single object type for all errors and fit all necessary info there or make it polymorphic or something. Anyway, what's so wrong and unobjectful about switching through some possible error types on an error_type field in your returned error object versus writing the same amount of catches for each possible exception object type you might catch? Don't want to check function (excuse me, method) return error type after each call? goto somewhere after a group of calls you would otherwise try and check there. That's what the compiler assembles anyway. But no. Passing objects by return is not enough. We also need to throw and catch them through some abstract, exceptional aether. There. Fuck exceptions**.
4. Magic numbers
Examples:
0xdeadbeef, 0xbaadf00d, and combinations thereof. Rotten.
0xcafebabe. Sexy.
0xfee15bad. It does. Fuck 1337*.
MZ. Sounds tough.
*). I remember when I was young and dreaming of optimal ways to represent text on 7-segment displays.
Bad examples:
for i from 13 to 69 do stuff with i involving 833 and 647.
My examples:
clock_divisor = 47; // because I say so, dammit! MY code, my clock! See (2).
And, the winner is:
123. Loop-switch sequence
for i from 1 to 3
if i is 1 do this
if i is 2 do that
if i is 3 do some other stuff
fuck autounindentation end for
Funny :D
Seen that in programming books. Bad, m'kay ?
**). Regarding abstracted and formalized exception handling, another reason why I tend to look down on object-orientation fanaticism is that everything is defined backwards. If I have a computer and it contains a 3D-accelerated graphics card, that's a subassembly. The GPU per-se is a subassembly of that card. But no, in OOP if I derive a class from another and add functionality, that's a subclass, and its parent is of course a superclass.*** And if I choose to draw that hierarchy in UML all the arrows have funny heads and generally point backwards. Of course, the inheritors are under (sub-) their parent, which is above (super-). So 'subclass' is not about its ability to substitute its superclass. It's about counterintuitive back-arrows. As you might have guessed, you actually can not generally substitute objects of a derived class in place of objects of the base class (inheritance is supposed to model the "sub is a super" relationship) and that's called the circle-ellipse or square-rectangle problem. (with square pronounced skwaah****, like Cartman: "So I kicked 'm skwaah- in the nuts!") Final solution suggested in linked article: change the paradigm.
***). Too bad you don't have #defines in Java. Then you could #define ultra super*****
****). skwåh?
*****). Credits: Wacky.
Of course, this also leads to reading articles of a more specialized nature.
One of these would be the article on anti-patterns. I find the 'Reinventing the square wheel' list entry the funniest :D
Note the smileycon used as sentence-terminating punctuation mark.
Anti-patterns are called so because in many (most?) cases they're bad, m'kay?
Not always.
1. Come From and Go To
(listed as 'Spagetti Code')
goto is useful, and is indispensable if programming in assembly language. Few processors support 'if' and 'for' and 'while' natively, most use jumps (gotos) to emulate them.
2. Busy Waiting
(spinning in a loop waiting for something to happen/finish instead of doing something else and waiting for a signal)
They taught this with great passion and emphasis in Operating Systems class. No busy waiting, use wait functions that yield control to another thread, halt the processor to sleep if it has nothing to do. Which is obviously reasonable. You don't want a task to spin doing nothing, you want it to sleep and let another one run. If none has anything useful to do, halt the processor to save power. That can't be anything but good, right?
Wrong. Turning on the processor to do useful stuff and then off while waiting for more stuff to do trashes the supply voltage by drawing large current spikes. In an improperly designed (or cheap) system, this can induce audible noises in the speakers, audible noises from power supply coils (hear them when scrolling text?) and electrical noise leading to poor measurement precision in embedded data acquisition systems. That's why all my microntrollers spin and never sleep. Many don't use interrupts at all and poll all peripherals except timing-critical ones. Waste of power? At some tens of milliwatts, from the mains and not from batteries, I couldn't be made to care. I own and control all tasks, I know how long they (should) take, I schedule them, I own all time and silicon Mwahaha, I spend 4 hours debugging. I rule :)
Also, spinlocks and atomic operations are good, m'kay. And well-documented.
3. Raising, catching and ignoring exceptions
(and all sorts of other problems)
Blah! What's wrong with just checking return values?
Why do we need exceptions? Certainly not because of abstraction and object-orientation.
If I ask you to please go take a shit, you can do it and reply with "Done." (return 0, or the more oxymoronic ERR_OK), or you can not do it and reply with "All portable toilets in range have their doors locked." (return ERR_NO_TOILET), or "No." (return ERR_GENERIC). I can then choose to check or ignore your return value, or just check to see if it's null. You can even return a pointer to an error object (supposing that the method halts on the first error encountered, use a list otherwise), though you would need some sort of RTTI to implement various types of errors just as you traditionally do with typed exceptions. But that can be messy, so you could just use one single object type for all errors and fit all necessary info there or make it polymorphic or something. Anyway, what's so wrong and unobjectful about switching through some possible error types on an error_type field in your returned error object versus writing the same amount of catches for each possible exception object type you might catch? Don't want to check function (excuse me, method) return error type after each call? goto somewhere after a group of calls you would otherwise try and check there. That's what the compiler assembles anyway. But no. Passing objects by return is not enough. We also need to throw and catch them through some abstract, exceptional aether. There. Fuck exceptions**.
4. Magic numbers
Examples:
0xdeadbeef, 0xbaadf00d, and combinations thereof. Rotten.
0xcafebabe. Sexy.
0xfee15bad. It does. Fuck 1337*.
MZ. Sounds tough.
*). I remember when I was young and dreaming of optimal ways to represent text on 7-segment displays.
Bad examples:
for i from 13 to 69 do stuff with i involving 833 and 647.
My examples:
clock_divisor = 47; // because I say so, dammit! MY code, my clock! See (2).
And, the winner is:
123. Loop-switch sequence
for i from 1 to 3
if i is 1 do this
if i is 2 do that
if i is 3 do some other stuff
fuck autounindentation end for
Funny :D
Seen that in programming books. Bad, m'kay ?
**). Regarding abstracted and formalized exception handling, another reason why I tend to look down on object-orientation fanaticism is that everything is defined backwards. If I have a computer and it contains a 3D-accelerated graphics card, that's a subassembly. The GPU per-se is a subassembly of that card. But no, in OOP if I derive a class from another and add functionality, that's a subclass, and its parent is of course a superclass.*** And if I choose to draw that hierarchy in UML all the arrows have funny heads and generally point backwards. Of course, the inheritors are under (sub-) their parent, which is above (super-). So 'subclass' is not about its ability to substitute its superclass. It's about counterintuitive back-arrows. As you might have guessed, you actually can not generally substitute objects of a derived class in place of objects of the base class (inheritance is supposed to model the "sub is a super" relationship) and that's called the circle-ellipse or square-rectangle problem. (with square pronounced skwaah****, like Cartman: "So I kicked 'm skwaah- in the nuts!") Final solution suggested in linked article: change the paradigm.
***). Too bad you don't have #defines in Java. Then you could #define ultra super*****
****). skwåh?
*****). Credits: Wacky.
Sunday, October 7, 2007
heartless
Today I feel unusually dark, cynical, unemphatic, insensitive, uncaring, angry, hateful, cruel, heartless. Heartless is a doubly inappropriate term in this case, as a) the heart is the source of emotion, just like the brain serves in cooling the body, and b) I am fully capable of feeling disgust, loathing, aversion, hate, as well as pleasure in others' suffering.
For example, I was reading about some big company testing their cosmetic products on animals. Well, I would feel a little bit safer if a product I'm using had been tested on something similar to my skin. Cruel and unethical to do that on rats or cute fuzzy rabbits, which are classified as pests? I agree. It would be ethical to test them on humans, both towards the animals and towards the end-users, who can be assured of a more reliable test. To the question of which humans should the products be tested on, I can only answer by pointing towards the ones who fanatically campaign for this idea that I fully endorse.
For example, I was reading about some big company testing their cosmetic products on animals. Well, I would feel a little bit safer if a product I'm using had been tested on something similar to my skin. Cruel and unethical to do that on rats or cute fuzzy rabbits, which are classified as pests? I agree. It would be ethical to test them on humans, both towards the animals and towards the end-users, who can be assured of a more reliable test. To the question of which humans should the products be tested on, I can only answer by pointing towards the ones who fanatically campaign for this idea that I fully endorse.
Subscribe to:
Posts (Atom)

