Click here to Skip to main content
15,891,607 members
Articles / All Topics

Programming Language Misuse

Rate me:
Please Sign up or sign in to vote.
4.24/5 (5 votes)
7 Sep 2017CC (ASA 2.5)2 min read 39.6K   2   12
Programming language misuse

I’m feeling a bit guilty about some code I wrote:

C#
using (new OperationTimer("MyOperation", this))
{
    // ... complete operation
}

This innocent looking C# snippet is hiding a tricky secret - the using statement is being misused (no pun intended). The documentation defines the intended usage clearly:

using Statement

  • Defines a scope, outside of which an object or objects will be disposed.

The problem? The notion of “object disposal” is being hijacked! In your garden variety IDisposable implementation, you’d be dealing with an external resource that needs to be released before the object can be removed from memory. Instead, I’m using it to time a block of code like so:

C#
class OperationTimer : IDisposable
{
    private readonly string _operationName;
    private readonly ITimable _obj;
    private readonly Stopwatch _stopwatch;

    public OperationWrapper(string operationName, ITimable obj)
    {
        _operationName = operationName;
        _obj = obj;
        _stopwatch = new Stopwatch();
        _stopwatch.Start();
    }

    public void Dispose()
    {
        _stopwatch.Stop();
        _obj.OnOperationCompleted(_operationName, _stopwatch.Elapsed);
    }
}

The constructor starts a timer and the Dispose() method stops it and reports the elapsed time. (Aside: if you’re interested in how I’m using the timer, check out my previous article Simplified Performance Counters.) There are certainly other ways to accomplish this same behavior, but they lack the elegance of a neatly scoped code block. It’s arguably an acceptable way to repurpose the language. In fact, the ASP.NET MVC authors saw fit to use it in a similar fashion with the BeginForm helper. The only “resource” it disposes of is to render a closing </form> tag.

My question is: When does repurposing language constructs turn from “acceptable language use” to a “dirty trick”, or worse, “illegible line noise”?

It seems like a slippery slope. One instance that I don’t care for is controlling execution flow by-way-of logical operator precedence in most C-like languages:

C#
expression1 && expression2 || expression3

Which is equivalent to:

C#
if (expression1)
{
    if (!expression2)
    {
        expression3
    }
}
else
{
    expression3
} 

This takes advantage of the order of evaluation in a logical statement – it is assumed (correctly) that expression2 will never be evaluated if expression1 is evaluated as false, and instead, expression3 will get to run. Likewise, if the first two evaluate to true, the truth value is known for the statement and expression3 is never evaluated. This is clearly not the intended usage which the language designers had in mind, but it works, and it saves any keywords from being written.

Some truly beautiful code has been written by way of hijacking the language. For instance, here’s a program that will calculate the value of pi using an ASCII circle. Truly neat - but also completely useless from a software development standpoint.

What do you think? Should I just get over my guilt about repurposing IDisposable? Or, should I be true to the original intent of the language and find another way?

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-ShareAlike 2.5 License


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralBoolean short circuiting is not misuse Pin
LintMan6-Apr-10 3:59
LintMan6-Apr-10 3:59 
AnswerRe: Boolean short circuiting is not misuse Pin
Flo Lee8-Sep-17 2:07
Flo Lee8-Sep-17 2:07 
GeneralCorrection regarding: expression1 && expression2 || expression3 Pin
RMessier29-Mar-10 18:55
RMessier29-Mar-10 18:55 
GeneralRe: Correction regarding: expression1 && expression2 || expression3 Pin
James Kolpack30-Mar-10 17:58
James Kolpack30-Mar-10 17:58 
GeneralNot a "dirty trick" but a great technique that improves robustness: RAII! PinPopular
wtwhite29-Mar-10 17:16
wtwhite29-Mar-10 17:16 
GeneralRe: Not a "dirty trick" but a great technique that improves robustness: RAII! Pin
torial31-Mar-10 9:07
torial31-Mar-10 9:07 
GeneralCaveats with "using" Pin
supercat925-Mar-10 4:45
supercat925-Mar-10 4:45 
GeneralRe: Caveats with "using" Pin
wtwhite29-Mar-10 17:43
wtwhite29-Mar-10 17:43 
GeneralRe: Caveats with "using" Pin
supercat931-Mar-10 7:27
supercat931-Mar-10 7:27 
wtwhite wrote:
Herb Sutter is a C++ guru who has written about the importance of not nesting object creation inside function calls or other object creations: http://www.gotw.ca/gotw/056.htm[^]


It's interesting to observe the relationship between sequence points and other parts of an expression. While some might find it odd that a compiler would interleave the handling of arguments, I can certainly imagine cases on some pipelined processors where a compiler might find it advantageous. It makes me wonder whether a void inline function which does nothing--totally ignoring its arguments--could ever improve code performance. For example, if a multiply takes several machine cycles to produce a result, but one can be started every cycle, could donothing(a=b*c, d=e*f, g=h*i); execute faster than {a=b*c; d=e*f; g=h*i;}?

Otherwise, the "problem scenario" in #4 was different from the one described; the issue I'm thinking of occurs if an object throws an exception during an implicit initializer (a combination of a declaration and an initialization). Since implicit initializers can't be wrapped in try/catch blocks, there's no nice way to unwind an object in such a scenario. In some cases a finalizer may be able to clean up the mess, but in other cases that wouldn't work.
GeneralRe: Caveats with "using" Pin
wtwhite31-Mar-10 15:24
wtwhite31-Mar-10 15:24 
GeneralRe: Caveats with "using" Pin
Ian Good6-Apr-10 22:03
Ian Good6-Apr-10 22:03 
GeneralSeems fine to me. Pin
dwilliss24-Mar-10 13:41
dwilliss24-Mar-10 13:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.