Category Archives: Development

Anything related to web development or software development.

Opera – A to Z: O

O is for Opera. No, not the music, I mean my favourite little web browser. (Yes, this is my one post in the A to Z Challenge that’s going to stray into the technical a teeny bit.) It’s usually included as one of the “top 5″ browsers, but most don’t take it very seriously as it doesn’t have a very large market share in most countries (though it does have over 50% market share in Belarus, and quite high usage in many other eastern European countries).

Opera browser logo

Opera browser logo; image from Wikimedia Commons

I first tried it out back when it was “adware” (from version 5), that is, you had to put up with an ad banner across the top of the browser unless you paid to get rid of it. I am usually all for free software (I won’t buy an MS Office license if LibreOffice can do everything I need), but Opera impressed me so much that I actually paid the $30 and bought the ad-free version. I’d been using Netscape before that but got annoyed by its infamous resizing bug and didn’t want to switch to IE because of how it was tied to MS’s operating systems (I used both Windows and Linux at home, Opera was happy on either). From version 8.5 on, it was completely free, and adding amazingly useful features with every major and minor release.

Norwegian company Opera Software ASA pioneered many of the features we take for granted in most other browsers today. It worked great out-of-the-box for normal users, but the customisations and tweaks you could do as a power user were just incredible.

Sadly, in an effort to better compete with other browser makers, Opera in 2013 decided to discontinue development of its “Presto” rendering engine with all its wonderful customisation options at version 12.16, and instead switched to “Blink”, the fork of WebKit from the Chromium project to which Chrome also switched. To do this, all features had to be slowly added back to Opera with each new release, starting at 15 and at version 20 at the time of writing this post (yes, they switched to a pretty much meaningless numbering system like Chrome and Firefox).

I currently use both version 12.16 (Presto) and version 20 (Blink), along with some other browsers for testing (I’m a web developer by day).

Some of my favourite features that Opera (Presto) had:

  • Every piece of the layout, every button, every one of its many toolbars was customisable and skinnable. You could make Opera look and work just the way you preferred.
  • Opera innovated so much: tabbed browsing (still better in Opera Presto than any other browser), CSS support, standards support, mouse gestures (like finger gestures in your smartphone? Opera had them way earlier), mouse and keyboard customisations, pop-up blocking, deleting private data, smart download management, RSS support, torrent support, speed dial, page zoom, sessions, and many, many more features it would take too long to list.
  • Opera’s CIO, Håkon Wium Lie, was one of the inventors and pioneers of CSS, which has made the web so much better in ways not only web developers can understand.
  • Back when (download) size mattered (i.e. smaller was better, most people were on dialup speeds), Opera’s power was packed into a tiny package compared to other browsers.
  • Opera has always been lightning fast, driving the speed competition and ruling the world speed-wise by an enormous margin… until Chrome began to pull ahead in some areas.
  • Opera’s built-in email client had revolutionary features, like storing emails in a database and allowing you to search based on tags that you could apply to emails, rather than using a folder-based system like the other email clients. This feature has now been made common (one could argue standard) by gmail.
  • Incredible flexibility across operating systems, mobile platforms from the latest Android to the oldest Java-enabled phone, and other devices from TVs to game consoles (Wii and DS).
  • Dragonfly, a very versatile and feature-rich inspector and debugger that I prefer to similar tools like Chrome’s inspector or Firebug.
  • Back in the days when too many webmasters and web developers still thought they should sniff browsers instead of features (google that if it doesn’t make sense), Opera allowed you to hide or mask as another browser, changing the user agent string on the fly to prevent being treated like a third-class browser.
  • It worked amazingly well when you ran it from a USB stick (e.g. at work, where you weren’t always allowed to install programs of your choice).
  • … and many more reasons that would take too long to list.

Oh yeah, can’t forget to mention Opera’s Bork edition. Back when the browser wars were raging and Microsoft thought it could get away with anything because it had had over 95% market share and figured it didn’t need to do anything to upgrade or improve its aging browser that was the bane of every web developer’s existence, the MSN website had the gall to feed Opera (and only Opera) a stylesheet that made it look bad, as though it was unable to cleanly render the MSN site. Opera’s complaints went unheard, so Opera responded by creating a special edition of its version 7 browser called the Bork edition, from the Swedish chef in the Muppets who always said, “Bork bork bork bork.” It fixed the display issues on MSN.com, but, more importantly, also turned the text on that site into words that sounded like that Swedish chef were reading the articles. I wish I had a screenshot of that to share, it was absolutely hilarious and made tech news headlines around the world.

Oooh, one more, then I really have to stop. Chrome came out with a fancy film advertising how its incredible speed made Google’s browser faster than a bullet:

Opera’s tongue-in-cheek response? Their browser is faster than a… potato:

Slightly less technical, but way funnier! :-D

Five aspiring authors in a cage

Most people would have read the “five monkeys in a cage” tale. If not, google it or (if you’re lazy), watch the summary on vimeo. Essentially, it is a tale encouraging us to question why things are sometimes done the way they are done with no apparent reason.

Five monkeys in a cage

Five monkeys in a cage (ok, the picture has more than five… it still gets the point across I think)

Today, I read fellow blogger Jodie Llewellyn’s nice post on “Adverbs… yes or no?” and I agree with her about adverbs getting a bad rap (not “wrap”, by the way ;-) ), but couldn’t help but notice that some of the comments there were fairly one-sided and “anti-adverb”. Is comparing people who advise against using adverbs to the five monkeys left in the cage a little extreme? Perhaps, but so is flat-out advising against the use of adverbs.

Adverbs are not evil, people.

As with so many things, the importance is to use adverbs in moderation. Granted, many of the commenters did advise moderation, and some pointed out why their overuse should be avoided. I don’t disagree with that. But saying their use is the “easy way out”, or a “shortcut”, that removing all adverbs from a manuscript makes it “stronger”, and that “said” should never be modified with an adverb? Really? I don’t want to offend anyone, and I don’t want anyone committing the strawman fallacy of claiming that I advocate liberal use of adverbs in all styles of writing (I don’t), but that just sounds like parochial adverb-bashing to me.

I also noted (with the slightest of smirks, I must admit), that those with adverb-allergies don’t mind using rather long adverbial phrases. How is that any better?

Journalism is probably an area where adverbs should be avoided more than in fiction. Sections in fiction where the reader should be left to fill the partially-drawn canvas with her own imagination should have fewer or no adverbs.

However, adverbs can (I stress can) be useful: they can clarify, modify, moderate, strengthen, explain; they can be elegant, precise, and more succinct than a laborious adverbial phrase. I suspect a number of adverb-despisers don’t realise how heavily they use adverbial phrases, and that sometimes – sometimes – a good adverb can be better. Adverbs have their place in first-person perspectives, for instance, where the narrator’s opinion should colour the reader’s impression.

I see close similarities between what is considered to be “good writing” and what is considered to be “elegant programming” (in my day job). Inexperienced writers, like inexperienced programmers, tend to sometimes follow certain patterns, or do too much or too little of something. Editors or code reviewers pick up on these patterns and, in formulating advice on how to prevent such anti-patterns, sometimes generalise a little too much, or state their advice as though it was doctrine. Such advice has its use, but experienced writers or programmers should take this advice with a hefty pinch of salt. The turkey city lexicon is a prime example. Know the rules, know the conventions, but also be aware of when and how they should be broken (or at least bent).

The comment that scared me into writing this post was one from a writer who said he was new to sharing his writing, hadn’t considered the use of adverbs too much, and now thought he should indeed remove adverbs to make his writing stronger. Please… let’s not create more monkeys who do things just because “that’s the way things are done around here”.

Pure CSS tooltips in WordPress.com

Another technical post; apologies to my followers who may be more interested in my writing category posts. In yesterday’s post, I wanted to include some information in a table, but, due to problems with the little available space, wanted to use “tooltips” – normally not a problem, when you have control over the site and can add JavaScript libraries and do fancy stuff with jQuery.

Need Tooltips, Have No JavaScript

But since I chose to conveniently have my blog hosted on wordpress.com (instead of writing it locally with wordpress.org and uploading it to another host, where I’d have full control over PHP, JavaScript, CSS, etc.), I’m limited to the custom CSS functionality, available from the dashboard (you may need to upgrade if you’re on the free version, sorry…) via Appearance > Customize. Luckily, I came across a stackoverflow question a few months ago that asked how to create tooltips (with HTML content, not just using the title attribute) without using JavaScript. To my surprise (I’ve been using various JavaScript libraries to produce nice tooltips on several projects but didn’t think a pure-CSS solution was even possible), someone had posted an answer describing how it could be done. The question was perhaps not phrased ideally, received several down-votes and was closed because “it wasn’t about programming”. I left a comment saying it should be re-opened and didn’t think about it again until last week, when I stumbled across the same question again. It was still closed, so I edited it to make it more apparent that it was a valid HTML/CSS question and flagged it for moderator attention so it could get re-opened. It worked, and now I found myself in need of trying it out on my blog.

Of course you can apply the same principles to any non-WordPress page where you have control over the HTML and CSS.

An Example

Hover your mouse over this paragraph to see an example of what I mean by a tooltip. It should pop up just below the paragraph.

This box is the tooltip; it can be styled with CSS to give it a different appearance.

So here’s a modified version of the solution posted on stackoverflow in the hope that it can help others looking to use tooltips on their wordpress.com pages.

Step One: The HTML

You need to fiddle with the HTML a little for this – if you don’t know what that means, you need to switch tabs on the top right of your editor from “Visual” to “Text”, which will show you a view with (some of) the HTML that will be used when your page is published.

Edit HTML on the "Text" tab

Switch to the “Text” tab to edit your page’s HTML

For each tooltip you want to create, you’ll need to have two nested tags with two classes: one for the visible tooltip “container” (the part that you have to hover over to reveal the tooltip), and one nested inside it for the initially hidden tooltip (which only becomes visible when you hover over the container. In my case, the tooltip container was a table cell (td) and the tooltip was in a generic container (a “div“):

<td class="tooltipContainer">
  This is the visible text, the tooltip container.
  <div class="tooltip">
    This is the hidden text, the tooltip contents that are only shown on hover.
  </div>
</td>

Instead of the table cell, it could of course also be another div.

Step Two: The CSS

If you were to preview the HTML changes without the necessary CSS, you’d see both the container and the tooltip, whether you hover or not. To edit your site’s CSS, go to “Appearance” and “Customize” from your dashboard’s menu.

Customize option from your menu

Accessing the “Customize” option from your dashboard’s menu

If you want, you can navigate to the post you’d like to try it out on, then select “CSS” from the menu on the right to open the CSS editor.

Editing your site's CSS

Editing your site’s CSS: from your dashboard, choose “Appearance”, then “Customize” on the left, then “CSS” on the right to open the CSS editor

Insert the following bit of CSS in the editor. (It needs to be added to your site only once; after that, any time you use a tag with class “tooltip” nested inside a tag with class “tooltipContainer”, the CSS will do the rest.)

.tooltipContainer {
  position: relative; /* add position offsets if required */
}

.tooltip {
  position: absolute; /* add position offsets if required */
  width: 200px; /* edit as required */
  background-color: black; /* edit as required */
  color: white; /* edit as required */
  border-radius: 5px;
  padding: 10px;
  opacity: 0;
  -webkit-transition: opacity .5s;
  -moz-transition: opacity .5s;
  -ms-transition: opacity .5s;
  -o-transition: opacity .5s;
  transition: opacity .5s;
}

.tooltipContainer:hover .tooltip {
  opacity: .8; /* edit as required */
}

.tooltipContainer .tooltip:hover {
  opacity: 0; /* optional */
}

Step 3: Customise As You Please

I’ve added comments to indicate where you can play around with values to suit your own taste; for instance, you can add positional offsets to have the tooltip appear somewhere other than below the container, or change the tooltip’s width, its colours, the opacity (I’ve made mine 80% opaque; change it to “1” if you don’t want it to be transparent. The last style I’ve added to hide (no opacity) the tooltip when you hover over where it appears (as opposed to hovering over the container), since it can be annoying to have it obscure other text), but of course you can just leave that part out if you want the tooltip to stay when hovered over (for instance, if you have a link in it and want people to be able to click on it).

Drawbacks? If a user has no mouse, e.g. on mobile devices, they don’t see the extra information because they don’t “hover”. Otherwise, it’s a clean CSS solution for functionality that normally requires JavaScript.

Feel free to let me know in the comments if you found this to be useful or if you have any questions. Enjoy!

Care for some Smalltalk in your Java, sir?

Time for a more technical post, related to my day job rather than my night job.

In my capacity as a web dev, I do server-side programming, mostly in Java. But my background from way back is in Smalltalk. Both are object-oriented languages, though there are several main differences (you may detect a hint of bias here):

    • Smalltalk is completely OO, Java is mostly OO.
    • Smalltalk doesn’t have “primitives” that aren’t objects, and even nil (unlike Java’s null) is an object.
    • Smalltalk is easy to learn initially, has the simplest syntax imaginable (simply “object message”, which always returns an object so you can chain), yet you can do so many things more elegantly than in any other language I know. Java comes with syntactical baggage from its C background, has many times more reserved keywords than Smalltalk’s five, and can be… cumbersome.
    • Smalltalk is what programming should be, Java is what programming is to most programmers (and here I’ll shamelessly bundle Java with C, dot Net, and so on).
    • Despite the above, Smalltalk is a niche language and Smalltalkers are a dying breed while other languages flourish.

I can imagine non-Smalltalkers smirking condescendingly by now, or at least sitting there with an eyebrow raised skeptically, wondering whether it’s worth reading on. If you are one of those, especially if you do Agile development, I’d recommend at least reading the shorter of the two articles I mention at the end of this post. (Plus, that way you’ll have to scroll past some Java code that may catch your interest after all.)

Occasionally while programming in Java, I find myself wishing that some of the Smalltalkish Ways Of Doing Things (TM) were available to me in Java. So, a while back (I think it was after I read that block closures had yet again been moved back to a future Java release), I decided to try to bring some Smalltalk into Java with a few simple little classes and methods. Do you absolutely need this? Not at all. Is it at least useful? Maybe, but probably only to some. Is it fun wrapping your head around different concepts and playing with something new? Heck, yeah. The complete source code is linked at the bottom of the post.

Some examples of defined methods

One of Smalltalk’s best features is the ability to pass around “block closures”, that is, to define a piece of code (with or without variables of its own) and to pass it to other objects or methods as though it were any other variable.

The easiest example works with an on-the-fly instance of java.lang.Runnable.

In Smalltalk, to do something with a block of code over a range of numbers, you’d use from:to:do:. The arguments are inserted after the colons, and typically parameters are prefixed with the article “a” or “an” to indicate that it’s just a possible value. (Personally, I think this makes code more readable in Java as well.) So the method definition could look like this: from: aStartingNumber to: anEndNumber do: aBlock. Let’s look at this translated to Java. We’ll use a Runnable instance as a simple no-argument block and simply iterate over the number range.

public static void fromToDo(int aFromIndex, int aToIndex,
    Runnable aRunnable) {
  for (int i = aFromIndex; i &lt;= aToIndex; i++) {
    aRunnable.run();
  }
}

To use Smalltalk’s timesDo: method, then, you’d simply call the method we’ve just defined with 1 as the from index.

public static void timesDo(int aNumber, Runnable aRunnable) {
  fromToDo(1, aNumber, aRunnable);
}

Now let’s get a bit trickier. We’ll use some collections (which have made their way to Java from Smalltalk, of course), some generics (because Java is strongly typed and wants to know types up front), and some reflection. The aim is to try and implement Smalltalk’s select: and reject: methods that operate on collections to select or reject elements that meet certain conditions. Since they’re rather similar, we’ll refactor the common code while we’re at it.

public static <ListType, ArgumentType> List<ListType> select(
    Collection<ListType> aCollection,
    BlockClosureBooleanWithOneArgument aBlockClosure) {
  return selectOrReject(true, aCollection, aBlockClosure);
}

public static <ListType, ArgumentType> List<ListType> reject(
    Collection<ListType> aCollection,
    BlockClosureBooleanWithOneArgument aBlockClosure) {
  return selectOrReject(false, aCollection, aBlockClosure);
}

private static <ListType, ArgumentType> List<ListType> selectOrReject(
    Boolean shouldSelect, Collection<ListType> aCollection,
    BlockClosureBooleanWithOneArgument aBlockClosure) {
  List<ListType> selectedValues = new ArrayList<>();
  for (ListType eachElement : aCollection) {
    if (eachElement == null && !shouldSelect || eachElement != null
        && shouldSelect == aBlockClosure.runWith(eachElement)) {
      // i.e. it's null and reject, or both true or both false
      selectedValues.add(eachElement);
    }
  }
  return selectedValues;
}

Note the other convention I’ve carried across from Smalltalk, to prefix variables used in an iteration with “each”, to emphasise that we do this for each value. The BlockClosureBooleanWithOneArgument we’re using is a simple interface defined as follows:

public interface BlockClosureBooleanWithOneArgument {
  public <ArgumentType> Boolean runWith(ArgumentType anArgument);
}

One more example before we get to how to use these methods. Smalltalk’s inject:into: is a wonderfully versatile method, but it can take a moment or two to wrap your head around it initially. You inject an initial value into a block of code, and execute this on a collection. So you have aCollection of things, and tell it, “starting with anInitialValue, execute aBlock on each of your elements”: aCollection inject: anInitialValue into: aBlock. (See how wonderfully the code reads almost like a simple English sentence, especially if you follow some simple naming conventions? Hence the name “Smalltalk”.) What would it look like in Java? Glad you asked. Here’s one possibility (I actually have two more implementations using reflection in my code which you can download below):

public static <ResultType, ListType> ResultType injectInto(
    ResultType anInitialValue, Collection<ListType> aCollection,
    BlockClosureWithTwoArguments aBlockClosure) {
  ResultType result = anInitialValue;
  for (ListType eachElement : aCollection) {
    result = aBlockClosure.runWith(result, eachElement);
  }
  return result;
}

Obviously BlockClosureWithTwoArguments is defined just like for one argument, except… with two. (I actually don’t like people starting method bodies with “result = …” and returning the result at the end, but in this case I don’t actually see a more elegant way. Maybe “updatedValue” would have been a better name than “result”?)

Some examples of how to use them

That’s all well and good, but the above examples wouldn’t be very useful without showing how they can be used. In my source code (see below), I’ve done this in a test class, both to show how the methods can be used and as a control of their correctness. The class with my Smalltalk code is called… drumroll… Smalltalk, while the test class is SmalltalkTest.

A very simple usage of from:to:do:, or fromToDo() since we’re looking at the Java version, could be to append a character a certain number of times (yes, you could use timesDo() for that, but let’s imagine we’re in code where we have the from index and to index and don’t feel like subtracting).

@Test
public void testFromToDo() {
  final StringBuilder builder = new StringBuilder("10as:");
  Smalltalk.fromToDo(1, 10, new Runnable() {
    @Override
    public void run() {
      builder.append('a');
    }
  });
  assertEquals("10as:aaaaaaaaaa", builder.toString());
}

To test our select() and reject() methods mentioned above in a simple use case, let’s use reflection to call the method startsWith() of the String class.

@Test
public void testSelectAndReject() throws Exception {
  String[] testStringArray =
      { "Test1", null, "Test 2", "", "Another Test",
          "Yet another test", "Test...3" };
  List<String> testStrings = Arrays.asList(testStringArray);
  String[] stringArrayStartingWithTest =
      { "Test1", "Test 2", "Test...3" };
  String[] stringArrayNotStartingWithTest =
      { null, "", "Another Test", "Yet another test" };
  List<String> stringsStartingWithTest =
      Arrays.asList(stringArrayStartingWithTest);
  List<String> stringsNotStartingWithTest =
      Arrays.asList(stringArrayNotStartingWithTest);
  Method startsWithMethod =
      String.class.getMethod("startsWith", String.class);
  List<String> selections =
      Smalltalk.select(startsWithMethod, testStrings, false, "Test");
  List<String> rejections =
      Smalltalk.reject(startsWithMethod, testStrings, false, "Test");
  assertNotNull(selections);
  assertNotNull(rejections);
  assertEquals(stringsStartingWithTest, selections);
  assertEquals(stringsNotStartingWithTest, rejections);
  assertEquals(stringsStartingWithTest.size()
      + stringsNotStartingWithTest.size(), testStrings.size());
}

If the lights all turn green on your tests, you know the code correctly selected the test strings that start with “Test” and rejected the others. (I’m using JUnit 4 here, which, you guessed it, comes from SUnit testing in Smalltalk, where all good things come from, including Agile development.)

Simple, yes. Let’s get trickier then. Everybody’s favourite example, the Fibonacci sequence, using injectInto() since it’s all about starting with a collection (in this case simply the set of natural numbers) and using them to inject an initial value into a simple algorithm to calculate the next value.

@Test
public void testInjectInto() throws Exception {
  Integer[] numberArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  List<Integer> numbers = Arrays.asList(numberArray);
  List<Integer> fibonacciList = new ArrayList<>();
  fibonacciList.add(1);
  Integer[] expectedArray = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
  Collection<Integer> expected = Arrays.asList(expectedArray);

  BlockClosureWithTwoArguments fibonacciBlock =
      new BlockClosureWithTwoArguments() {
        @SuppressWarnings("unchecked")
        @Override
        public <ReturnType, FirstArgumentType, SecondArgumentType>
            ReturnType runWith(
                FirstArgumentType aFirstArgument,
                SecondArgumentType aSecondArgument) {
          List<Integer> eachList = (List<Integer>) aFirstArgument;
          Integer eachIndex = (Integer) aSecondArgument;
          Integer lastNumber = eachList.get(eachIndex - 1);
          eachList.add(lastNumber
              + (eachList.size() > 1 ? eachList.get(eachIndex - 2)
                  : 0));
          return (ReturnType) eachList;
        }
      };

  assertEquals(expected,
      Smalltalk.injectInto(fibonacciList, numbers, fibonacciBlock));
}

Not nearly as tricky as it may look at first glance – just think about how the sequence works and it should become obvious. We’re starting with a list that initially only has a “1” in it and, in each iteration, adding to the list the sum of the last two items in the list (or just the last one if there’s only one to take care of the base case). It’s not the sort of thing you typically do in everyday coding, but I’m sure if you look for it, you’ll spot opportunities where something like this could be useful. Keep in mind that the definition of your code block, however complex, only needs to be done once; the code can then be re-used wherever needed in a quick one-line call.

Show’s over

That’s pretty much it. If you’d like to, take a closer look by downloading the full source code. Feel free to download/use/ignore as you see fit. It has the following Java methods (some with several versions) and unit tests based on the original equivalents Smalltalkers will recognise:

    • fromTo()
    • fromToDo()
    • fromToDoWithIndex()
    • timesDo()
    • doWith()
    • select()
    • reject()
    • collect()
    • detect()
    • contains()
    • includes()
    • injectInto()

If you spot any mistakes, have any suggestions, improvements, or any other comments/questions, please let me know below in the comments.

Finally, I’d like to direct anyone who may be interested to two great articles I’ve found that have really resonated with me.

Why Smalltalk isn’t just “another language”, written by Dafydd Rees in 2010. Not all that long, but makes some great points about Smalltalk and Agile.

Why Java Isn’t Smalltalk: An Aesthetic Observation, written by Sigrid E. Mortensen back in 2001 (so old, in fact, that the only place I still found it is in an archived version of the original site). It’s a fair bit longer, but well worth the read, as it makes some excellent points about the value and impact of losing elegance and simplicity in programming.

Cheers,

AMC

Follow

Get every new post delivered to your Inbox.

Join 204 other followers