Montag, 29. Februar 2016

DRY or not DRY

I found a blog post recently that stated (among other things) that the author of that post considered the application of the DRY principle to create a dependency. As one of his highest values was to avoid dependencies, he often refused to do DRY-refactorings.

On first sight this sounds reasonable.

On the second it doesn't: If there is a place in your code that allows for a DRY refactoring, then that already IS a dependency! Remember that DRY tells us to have logic that means the same (=tries to accomplish the same) only once. So, if two places in code try to accomplish the same, they are implementations of the same requirement. If that requirement changes - well, there are two places to change in code making those two places linked. The problem with this is that it is usually not visible and thus easy to forget! The DRY refactoring (=extracting the code in question into a function) just makes that dependency explicit; it does not create a new one. Well, I certainly prefer an explicit dependency over an implicit one...

While I agree that not every DRY refactoring should actually be made; I think the dependency-argument does not hold...

Freitag, 29. Mai 2015

Fixing everything two ways

Today I had an ugly programming problem where it looked like an object in the code "forgot" members. Well it turned out that this member variable did not forget anyting - it was simply replaced in an unexpected place in the code. The problem could be solved easily after I had discovered that. All very oscure and nerve wrecking and it took me more than 2 hours for something that should have taken just a few minutes.

When I thought about the problem afterwards it occured to me that it would be good to also take care of this replacement problem, because it was far from obvious and I might run into the problem again. So I went back in and spent another 7 minutes (!) making this replacement problem go away (now it is not a member any more, but an argument to a method - because it is only needed by this one method). I'll now never have this problem again...(Yeah, basically this was bad design in the first place, but hey, that code was almost 10 years old... ;-)

All this made me think of an old article by Joel spolsky and made me realize - fixing stuff two ways is more universally useful than just for customer service...

PS: um, well this is also a variation of the Boy Scout Rule.

Dienstag, 18. Februar 2014

My LED-light Experiment

A while ago I experimented with LED-Bulbs to see if the could help me lower the energy footprint of my house. Just by replacing a few bulbs (far from all, and not all to LED!), I easily threw out 181Watts (that is if all of these bulbs burn at the same time - which is practically never the case) and in some places it is now even brighter than before. A reduction of about 2/3's and there's still potential. Here are a few things I've learned:
  • Finding the right Wattage for your bulbs is difficult. There are some tables online that help you (Watts to Lumen), but that's only a hint and you will have to experiment to find the right number. Both numbers do not help you find out how the light will "feel". A real problem, when buying online.
  • LED light bulbs are surprisingly heavy. And some LED-Bulbs are actually huge, so buying on the internet might give you some surprises.
  • If you really want to save energy check the lm/W-ratio of the bulbs you want to use. There are big differences... The top ones are above 100 lm/W (classic bulbs: 10-15 lm/W).
  • 12V-Systems are a bit tricky. I burned a transformer, although a friend "who should know" told me that was impossible. Maybe it is, but you may still have to change it, because transformers have a minimum power usage requirement that you might not hit with your LEDs: I have a 2x10W-halogen-lamp that does not light up, when I replace one of the bulbs with a 2W-LED (it just flashes about once a second). Note also that the transformer I bought had a little paper that told me that you should buy a LED-transformer with the bulb-wattage times 1.5! So for my 4x2W-kitchen-lighting, I'll need at least a 12W transfomer. I did not know that before... I've also heard of LEDs flickering with older transformers - but I have not seen that myself.
  • The light from LEDs feels definitely colder than from classic bulbs. There are really good bulbs that try to overcome that; and this will most likely get better in the future. But for now, you'll have to experiment (and ask the rest of the family) if you can live with that. I'd say the light is comparable to those energy-saving bulbs (CFLs??), and I would recomment to use LEDs istead of those because they do not contain mercury (=health problem) and they cannot really explode (no vacuum). There are even ruber-led-bulbs that you probably can play Squash with... ;-)
  • LEDs are advertised as having 100% light immediately - that's not entirely true: Many bulbs have a initialization time that is noticeable but well below a second. But you can see ist. I also find interesting that the opposite is true: LEDs are immediately dark, when you switch them off! When experienced for the first time, this is a bit creepy, because you probably did not notice that is different from classic bulbs: they glow out. Subtle, but different.
  • The bigger problem is that LEDs emit light into a specific direction. This is the reason why you should have a look at the angle of radiation of your targeted bulb. The best fit for LEDs are spotlights! IMHO if LEDs take off more, we'll see a lot more indirect lighting, because it is simply easier to build them with LEDs. When replacing a classic bulb in special lamps you might end up with only half of the room lit. I have that in a few wall-lamps where the bulb is attached horizontally - there are not many LED-bulbs that are usable there.
  • LED Bulbs not really stay cold - they do get warm; but you most likely will not get burns...
  • Don't even think of hybrid solutions for a certain multi-bulb-lamp - i.e. mixing classic bulbs with LEDs (Thinking you want to have the warm light of classic bulbs and the savings from an LED). It just does not look good because you can see the difference. This is worse for dimmable lamps, because LEDs and classic bulbs have a different dimming curve. Believe me, it is ugly. If you don't like the LEDs light color - stay with classic bulbs.
  • There are a lot of crap-led-bulbs out there.
  • Don't expect too much money saving from replacing the bulbs, because if you're like me, then lighting is not the biggest consumer of energy in your house. Especially considering the price of an LED-Bulb, it might take a few years to break even with normal bulbs. But: the longer the bulbs burn per day, the faster you save. Tip: Actually try to find out how long (per day) the bulbs are used, and remember that this changes through the year (unless you live near the equator...). Then replace the ones with the highes usage and actually do some calculation; this is the most economic way to do it. Replacing a 25W bulb in the food storage that burns a few minutes a day at max will probably take a century to save anything...
  • It does not have to be LED: Shame on me - I still found 60W classic bulbs in my house. Replacing them with 42W-Halogens gives about the same amount of light (in almost the same color), but already use a lot less energy. There is basically no reason not to do at least this!

Samstag, 15. Februar 2014

Reorganizing class internals

A lot of code I looked at has the private stuff of a class on top (I'll say private in the following, meaning everything invisible from the outside like protected, internal...). The code starts basically with a section of the member variables, followed by private functions. In many cases then starting to mix public and private members. I dont know if that's really universal, but a lot of my collegues seem to do it that way.
I did, too.
I guess thats something we learned from older languages like Delphi where everything needs to be defined before it can be used; and as the public members will most likely call or use the private ones, the private stuff has to come first. More modern languages like Java and C# do not require that any more, be we stick to old habits. But... Is that good?
I now tend to say NO, because the most important thing of a class is its public interface. So THAT should come first. Private members are just details of the implementantion, and only need to be looked at when you want to find out HOW the class is doing what it's doing. But that's usually interesting after you know WHAT the class is supposed to do (which the public interface should tell).
After a few experiments in smaller projects this actually seems to work for me. Now I'll try to use that in bigger ones.
I'll keep you updated if it keeps working for me.
What do you think?

Freitag, 16. August 2013

East Bound Coding

Today I gave myself a little kata to work at (namely Happy numbers from the CCD-School).

That in itself is not so special. The real fun started after I technically finished the kata.

A few days ago I read blog posts about "Tell, dont ask", and a related idea called something like "east oriented [coding]". The basic idea is that all data should "travel east" in the code. This is what I liked to try and it has two main implications for the code:

  1. it effectively forbids assignments, because that lets the data travel west (var x=SomeFunction(); calculates the result, and then stores it in x - which is "west" of the call).
  2. functions return void; which only lets you get stuff done by using continuations (Note: this is an exaggeration of the original concept, which talks about object orientation and methods that should return void or the result object; However in the context of this blog let me stay without return values...).
That sounds like live will get functional - and I regret having started the kata with C#...

The initial solution consisted of a function that returned whether the number is happy, or not:

  bool IsHappy(int p) { ...
Clearly west bound; so I change it to
  void IsHappy(int p, Action<int> act) { ...
which immediately breaks all tests. No surprise.

(As a side note: I actually first had an Action<bool> in it but it turned out that the bool is not very helpful. The called action function would know that something is happy, but not which number. It seemed to make way more sense to only call the action when the number is happy; with that number as an argument)

Ok, I change the first test from

  Assert.IsTrue(IsHappy(1));
to
  IsHappy(1, x => Assert...
um, no that would not work because it would pass even if the lambda was never called. So how do you check whether a function is never called? The action needs to leave something that I can check; like this:
  var called = false;
  IsHappy(1, x => called = true;);
  Assert.IsTrue(called)
However, this is west bound again. The assignement, you know... The solution I found uses an exception. Let the test expect an exception, and the call throw one. If its never called - it fails because of the missing exception. Interestingly this is less code, although it feels odd to throw an exception when things work:
  [ExpectedException(typeof(Exception))]
...
  IsHappy(1, x => { throw new Exception(); });
The negative tests are easier, they just Assert.Fail() when the lambda is called.

The actual algorithm is pretty easy to convert: basically replace all return(s) by the call to our continuation action or dont do anything. However, what bit me first after that was that - other than the return statement - this call obviously returns. This creates a few surprises, but is easily fixed.

Next the test that checks the returned value fails - it is always one. Crap. After the first recursion the function does not know the initial value any more and as 1 is the value that stops the recusion - this is what always is passed on. This calls for a helper function to keep that value in the loop. Noteworthy that this is easier in functional languages such as F# or lisp where you can use local functions; possible in c# as well, but it looks a little ugly (and has an assignment because the function needs a name when you like to recurse; well, if you do not resort to y- or z-combinators...). No use bothering with further detail... here is the final code of my solution (without the tests):

  public void IsHappy(int value, Action act)
  {
    IsHappyHelper(value, value, act);
  }

  private void IsHappyHelper(int value, int current, Action act)
  {
    if (current == 4) return;

    if (current == 1) act(value);
    else CalcNext(0, current, x => IsHappyHelper(value, x, act));
  }

  private void CalcNext(int sumsofar, int p, Action act)
  {
    if (p <= 0) act(sumsofar);
    else CalcNext(sumsofar + (p%10)*(p%10), p/10, act);
  }

All in all:

  • I was surprised that the resulting code was not much different than the "normal" one; after some fiddling even shorter (except for the function signature which is obviously more complicated).
  • Interestingly the boolean (the return value of the original function) is completely gone! Now the function is just a filter that only lets happy numbers get through. If the false-case is also needed, the function might be extended to accept another call in that case (affects only the first if in the helper). Um, yeah, would not really help readability. In one of my tests this even made the code shorter: from
    if(IsHappy(idx) result.Add(idx)
    to
    IsHappy(idx, result.Add)
  • I did not plan for it, but the functions now only have one position where the code sends the result away, while the initial code had several "return x"'s. Don't know if this is good or bad...
  • I do not like the lambda to change the signature in IsHappyHelper. An F# version is much nicer, as it can use a local function with the correct signature (if a binding is not counted as an assignment...)
  • In post mortem I realize that an action signature of might have been closer to the original solution, and might have saved me from the trouble with the asserts. Well... maybe not.
  • IsHappy is now actually a bad name. Probably IfHappy would do now!?

Disclaimer: This was an experiment! That means I did stuff here, that I would not normally do in production code. I also know that Tell-dont-ask and east-bound are originally object oriented; in this kata I kind of used them in a functional context. DO try this at home... ;-)

Dienstag, 9. Oktober 2012

Programming by Accident

Programming by accident is an anti pattern of software development. Until yesterday I thought it was obvious to avoid doing that - but I learnt that it's really easy to do it without event noticing. See how:
  1. Last week I was working on a small .net library. The AssemblyVersion in it was set to "1.2.0.*", because I did not really care about the revision number, and wanted to get rid of the responsibility to count it up manually.
    One day I left happy that my .net bridge was working as expected. When I resumed my work the next day, I made a small change, and ... the library did not even load. Instead I got "ole error 80131040".
    After what seemed an eternity of trying and googling I found that the library simply did not load, because the revision number was lower than the day before while the runtime was expecting the same revision or higher. According to the documentation the '*' in my AssemblyVersion was replaced by half the number of seconds since midnight. Well, that explained why it was lower than the day before...
    So, what was my mistake here? I was programming by accident, because I assumed I knew what the little asterisk was doing. And I had never looked into how .net works with the Assembly- and AssemblyFileVersions.
    The software had only looked like it was working correctly...

  2. In that library I made use of the shift operarator (<<). Hey, what can possibly go wrong with a shift? So, I made a loop that shifted a single bit through an integer until it was shifted out:
        int x = 0;
        do {
          y = 1 << x;
          Dostuff(y);
          x += 1;
        } while(y != 0);
    Well, turns out I created an infinite loop (disclaimer: I did not notice that initially, because the loop and conditions were actually a little more complicated than shown here; this example is quite constructed to show the underlying problem). The shift operator simply does not accept values that would shift all bits out; it does a secret '&31' and the shift distance. So when x hits 32 it actually does an 1<<0 again and y never turns 0.
    Again some programming by accident and also (I have to admit) a little bit of trying to be clever. Both tend to fall on your feet - and did.

Assuming a thing does what you think it does is programming by accident. And it can happen in the smallest of places...