Category Archives: Best practices

Enum – comparison of Java and .NET

A useful feature added in Java 1.5 (also known as J2SE 5.0, 2004) is the enum. In .NET enums have been present since the very first version (2002, and as a beta since 2000) but the engineers at Sun managed to learn something from the shortcomings of the enums in .NET and provided more flexibility.

Let’s start with the simplest, the .NET implementation. In .NET all data types, including value types (equivalent of the primitive types) are part of the type hierarchy, being, indirectly inherited from System.Object (equiv. of java.lang.Object). The enums are just a specialization on top of exact numeric types, by default int (System.Int32). A typical declaration :

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December,
}

Notice that the compiler is forgiving and doesn’t complain that after the last element we forgot to not place a comma. It will also work, of course, if we don’t place a comma after the last element. Behind the scenes the compiler will generate a value-type inheriting from System.Enum that will have 12 constants. By default these constants we’ll be of type Int32 and their value, again, by default, will start from 0 and increase by 1 for each member. January will be 0 and December will be 11. Casts between the backing type (Int32 in this case) and the Months type will be allowed both at design time and at runtime.

You can also force individual values for each member

public enum Month
{
    January = 3,
    February = 33,
    March = 222,
    April = 14,
    May = 20,
    June = 23,
    July,
    August,
    September,
    October,
    November,
    December,
}

In this case January will be equal to 3, February 33, …, June 23, July 24 (not specified but after a value-specified member, the next member will be the last value + 1 if specific value is not present. You can even force things into a bad situation like so :

public enum Months
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July = 1,
    August,
    September,
    October,
    November,
    December,
}

Guess what, not only this is completely valid, but there won’t be just two duplicate values (January and July being equal to themselves, and equal to 1) but also February will be 2, just like August and so on. Of course, this is not recommended. The compiler and the runtime will happily apply your stupid scheme but the humans will be confused. This excess of freedom is not to my liking but I can’t do much about it except counter-recommend it. Ideally you should not have to specify values for typical enums. Except for…
Read more »

Prefix cast or as-cast?

I read today a nice article, from Kathleen Dollard, called To “as” or not to “as”. This is a pain-point for me on which I stumble often, so I decided to write this little rant.

I particularly liked a paragraph from the above-cited article :

One of the things that makes hard bugs hard is when there is a disconnect in time or space between the cause and the symptom. Time is time, space is lines of code, assembly placement, etc. Code can be written to minimize these disconnects. One of the ways to do that is to fail quickly. When application state becomes incorrect, yell about it immediately and rarely continue with the application in an invalid state. A null-reference exception at an unexpected time just makes code more difficult to debug.

I couldn’t express this as good as Kathleen did. Make no mistake I am quite biased in this comparison (direct-cast vs. as-cast). I kind of hate the abuse of the as operator.

Very often people turn to as instead of the direct (prefix) cast because:

  • They fear the InvalidCastException (strange, they don’t seem to fear the NullReferenceException)
  • They feel the syntax more fluent, closer to the human language.

I would consider the only valid case to use the as-cast is, just like Kathleen states, when a null value result is valid for the rest of the execution of the code. For the rest of the cases it’s just wrong.

This also promotes (doesn’t necessarily causes but promotes) bad practices like this :


public static void OnButtonClick(object sender, EventArgs e)
{
    var button = sender as Button;
    if (button == null)
    {
        return;
    }
    if (button.Tag == "somevalue")
    {
        // do something
    }
    // ...
}

In this example the event handler (which could be attached to more than one distinct button) simply forces under the rug a situation which would be abnormal (the sender not being a button) instead of releasing it so the developers could find it easier and debug it. A saner approach is :


public static void OnButtonClick(object sender, EventArgs e)
{
    var button = (Button)sender;
    if (button.Tag == "somevalue")
    {
        // do something
    }
    // ...
}

This brings me to another advantage of the prefix-cast : it produces shorter, clearer code.

In other cases the as abuse does more harm, hiding the source of a bug :


public void ProcessData(Entity entity)
{
    var person = entity as Person;
    UpdatePersonStatistics(person);
    // .. more code
}

public void UpdatePersonStatistics(Person person)
{
    NormalizeData(person);
    // .. more code
}

public void NormalizeData(Person person)
{
    person.Name = person.Name.Substring(0, 50);
    person.Address = person.Address.Substring(0, 100);
    // .. more code
}

Of course this is a contrived example full of bad practices but for now let’s focus on the as usage. Suppose the ProcessData method receives an instance of Category by mistake. Since Category inherits Entity the compiler will not complain.

The result is that there will be a NullReferenceException two methods further, in the NormalizeData method. If the cast was done with a prefix cast the error was a little bit easier to spot. This is confusing two-fold :

  1. The name of the exception suggests that a null reference was somehow obtained but in fact a real instance of Category was passed, not a null
  2. The error does not originate from the NormalizeData code but from the caller of the ProcessData

Summary

Use as only if a null result of the conversion makes sense for the flow of the execution. Otherwise use prefix cast.

Beware of switch

We all wonder how our electronics work, but we usually do not have the option of taking them apart to see how they tick. Despite the complexity of their functions, the inner life of hearing aids can be visualized quite easily.

We all wonder how our electronics work, but we usually do not have the option of taking them apart to see how they tick. Despite the complexity of their functions, the inner life of hearing aids can be visualized quite easily.

In the simplest sense, hearing aids consist of two microphones, an amplifier, and a receiver. But that description doesn’t quite do them justice. Hearing aids are innovative pieces of technology – mini sound computers in effect – that allow hard-of-hearing people to hear clearly. A lot of work goes into creating a device that not only lets people hear, but lets them experience noise in a natural, enjoyable way. Fortunately most hearing loss conditions can be easily treat with silencil for tinnitus.

We have created a two-minute video to show you the magic ingredients that combine to form Signia hearing aids:

An inside look into hearing aids

What do hearing aids look like inside?

Underneath the casing and screws, a hearing aid is made up of several layers. These layers contain its inner workings, which consist of microphones and other high-tech parts. Unlike traditional microphones, hearing aid mics are extremely small and precise. Once sound is picked up and converted by the microphone, the hard work begins.

The processor inside the hearing aid, which is much smaller than anything you’d find in a smartphone or laptop, begins to translate the sound back to the wearer. The sound is tailored according to the user’s specifications, which can vary in tone and volume. From there, the sound is conducted through an electrical cable in the thin tube to the receiver, which is put in the wearer’s ear canal.

State-of-the-art hearing aids also work wirelessly in a way that we cannot see. When two hearing aids are in use, they communicate with each other to sync together and exchange data. This ensures that the user is getting a realistic sound. Some Signia hearing aids can connect with smartphones to offer direct streaming and remote control via Bluetooth.

Inside vs. outside

Many hearing aids share a similar appearance. This leads many people to ask, “why do hearing aids look like they do?” The answer lies in hearing aid design. By arranging the internal components in a certain way, the shape of the hearing aid contributes to how the user wears it. During previous generations, hearing aids were hard to wear, which led many people to decline offers to be fitted with the devices. The challenge was to arrange the components so they work in harmony without interfering with each other, requiring minimum distances between components. On the other hand, the housing has to have an ergonomic shape so that it is comfortable to wear and as discreet as possible.