DaedTech

Stories about Software

By

Don’t Take My Advice

A Brief History of My Teeth

When it comes to teeth, I hit the genetic jackpot. I’m pretty sure that, instead of enamel, my teeth are coated in some sort of thin layer of stone. I’ve never had a cavity and my teeth in general seem impervious to the variety of maladies that afflict other people’s teeth. So this morning, when I was at the dentist, the visit proceeded unremarkably. The hygienist scraped, prodded, and fluoridized my teeth with a quiet efficiency, leaving me free to do little but listen to the sounds of the dentist’s office.

HygienistThose sounds are about as far from interesting as sounds get: the occasional hum of the HVAC, people a few rooms over exchanging obligatory inanities about the weather, coughs, etc. But for a brief period of time, the hygienist in the next station over took to scolding her patient like a child (he wasn’t). She ominously assured him that his lack of flossing would catch up to him someday, though I quietly wondered which day that would be, since he was pushing retirement age. I empathized with the poor man because I too had been seen to by that hygienist during previous visits.

The first time I encountered her a couple of years ago, she asked me if I drank much soda, to which I replied that I obviously did since my employer stocked the fridge with it for free. I don’t drink coffee, so if I want to partake in the world’s most socially acceptable upper to combat grogginess, it’s Diet Pepsi or Mountain Dew for me. She tsked at me, told me a story of some teenager whose teeth fell out because he had a soda fountain in his basement, and then handed me a brochure with pictures of people’s mouths who were apparently ravaged by soda to such a state where I imagine that the only possible remedy was a complete head transplant. My 31 year steak of complete imperviousness to cavities in spite of drinking soda was now suddenly going to end as my teeth fell inexorably from my head. That is, unless I repented my evil ways and started drinking water and occasionally tea.

I agreed to heed her advice in the way that one generally does when confronted with some sort of pushy nutjob on a mission–I pretended to humor her so that she would leave me alone. When I got home, I threw out the Pamphlet of Dental Doom and didn’t think about her for the next six months until I came back to the dentist. The first thing that she asked when I came in was whether I was still drinking a lot of soda or not. I was so dumbfounded that I didn’t have the presence of mind to lie my way out of this confrontation. I couldn’t decide whether it’d be creepier if she remembered me from six months ago and remembered that I drank a lot of soda or if she had made herself some kind of note in my file. Either way, I was in trouble. The previous time she had been looking to save the sinful, but now she was just pissed. Like the man I silently commiserated with this morning, she proceeded to spin spiteful tales of the world of pain coming my way.

Freud might have some interesting ideas about a person that likes to stick her fingers in other people’s mouths while trying to scare them, and I don’t doubt that there’s a whole host of ground for her to cover on the proverbial therapist couch, but I’ll speak to the low hanging fruit. She didn’t like that I ignored her advice. She is an expert and I am an amateur. She used her expertise to make a recommendation to me, and I promptly blew it off, which is a subtle slap in the face should an expert choose to view it that way.

It Isn’t Personal

It’s pretty natural to feel slighted when you offer expert advice and the recipient ignores it. This is especially true when the advice was solicited. I recall going along once with my girlfriend to help her pick out a computer and feeling irrationally irritated when we got to the store and she saw one that she liked immediately, losing complete interest in my interpretation of the finer points of processor architectures and motherboard wiring schemes. I can also recall it happening at times professionally when people solicit advice about programming, architecture, testing, tooling, etc. I’m happy–thrilled–to provide this advice. How dare anyone not take it.

But while it’s often hard to reason your way out of your feelings, it’s a matter of good discipline to reason past irrational reactions. As such, I strive not to take it personally when my advice, even when solicited, goes unheeded. It’s not personal, and I would argue it’s probably a good sign that the members of your team may be nurturing budding self-sufficiency.

Let’s consider three possible cases of what happens when a tech lead or person with more experience offers advice. In the first case, the recipient attempts to heed the advice but fails due to incompetence. In the second, the recipient takes the advice and succeeds with it. In the third and most interesting case, the recipient rejects the advice and does something else instead. Notice that I don’t subdivide this case into success and failure. I honestly don’t think it matters in the long term.

In the first case, you’re either dealing with someone temporarily out of their depth or generally incompetent, who might be considered an outlier on the lower end of the spectrum. The broad middle is populated with the second case people who take marching orders well enough and are content to do just that. The third group also consists of outliers, but often high-achieving ones. Why do I say that? Well, because this group is seeking data points rather than instructions. They want to know how an expert would handle the situation, not so that they can copy the expert necessarily, but to get an idea. Members of this group generally want to blaze their own trails, though they may at times behave like the second group for expediency.

But this third group consists of tomorrow’s experts. It doesn’t matter if they succeed or fail in the moment because, hey, success is success, but you can be very sure they’ll learn from any failures and won’t repeat their mistakes. They’re learning lessons by fire and experimentation that the middle-of-the-roaders learn as cargo cult practice. And they’re not dismissing your advice to offend you–they earnestly want to understand and assimilate your expertise–but rather to learn from you.

So when this happens to you as a senior team member/architect/lead/etc., try to fight the urge to be miffed or offended and exercise some patience. Give them some rope and see what they do–they can always be reigned in later if they aren’t doing well, but it’s hard to let the rope out if you’ve extinguished their experimental and creative spirit. The last thing you want to be is some woman in a dentist’s office, getting irrationally angry that adults aren’t properly scared of the Cavity Creeps.

By

Subtle Naming and Declaration Violations of DRY

It’s pretty likely that, as a software developer that reads blogs about software, you’ve heard of the DRY Principle. In case you haven’t, DRY stands for “Don’t Repeat Yourself,” and the gist of it is that there should only be one source of a given piece of information in a system. You’re most likely to hear about this principle in the context of copy-and-paste programming or other, similar rookie programming mistakes, but it also crops up in more subtle ways. I’d like to address a few of those today, and, more specifically, I’m going to talk about violations of DRY in naming things while coding.

DRY

Type Name in the Instance Name

Since the toppling of the evil Hungarian regime from the world of code notation, people rarely do things like naming arrays of integers “intptr_myArray,” but more subdued forms of this practice still exist. You often see them appear in server-templated markup. For instance, how many codebases contain text box tags with names/ids like “CustomerTextBox?” In my experience, tons.

What’s wrong with this? Well, the same thing that’s wrong with declaring an integer by saying “int customerCountInteger = 6.” In static typing schemes, the compiler can do a fine job of keeping track of data types, and the IDE can do a fine job, at any point, of showing you what type something is. Neither of these things nor anyone maintaining your code needs any help in identifying what the type of the thing in question is. So, you’ve included redundant information to no benefit.

If it comes time to change the data type, things get even worse. The best case scenario is that maintainers do twice the work, diligently changing the type and name of the variable. The worst case scenario is that they change the type only and the name of the variable now actively lies about what it points to. Save your maintenance programmers headaches and try to avoid this sort of thing. If you’re having trouble telling at a glance what the datatype of something is, download a plugin or a productivity tool for your IDE or even write one yourself. There are plenty of options out there without baking redundant and eventually misleading information into your code.

Inheritance Structure Baked Into Type Names

In situations where object inheritance is used, it can be temping to name types according to where they appear in the hierarchy. For instance, you might define a base class named BaseFoo and then a child of that named SpecificFoo, and a child of that named EvenMoreSpecificFoo. So EvenMoreSpecificFoo : SpecificFoo : BaseFoo. But what happens if during a refactor cycle you decide to break the inheritance hierarchy or rework things a bit? Well, there’s a good chance you’re in the same awkward position as the variable renaming in the last section.

Generally you’ll want inheritance schemes to express “is a” relationships. For instance, you might have Sedan : Car : Vehicle as your grandchild : child : parent relationship. Notice that what you don’t have is SedanCarVehicle : CarVehicle : Vehicle. Why would you? Everyone understands these objects and how they relate to one another. If you find yourself needing to remind yourself and maintainers of that relationship, there’s a good chance that you’d be better off using interfaces and composition rather than inheritance.

Obviously there are some exceptions to this concept. A SixCylinderEngine class might reasonably inherit from Engine and you might have a LoggingFooRetrievalService that does nothing but wrap the FooRetrievalService methods with calls to a logger. But it’s definitely worth maintaining an awareness as to whether you’re giving these things the names that you are because those are the best names and/or the extra coupling is appropriate or whether you’re codifying the relationship into the names to demystify your design.

Explicit Typing in C#

This one may spark a bit of outrage, but there’s no denying that the availability of the var keyword creates a situation where having the code “Foo foo = new Foo()” isn’t DRY. If you practice TDD and find yourself doing a lot of directed or exploratory refactoring, explicit typing becomes a real drag. If I want to generalize some type reference to an interface reference, I have to do it and then track down the compiler errors for its declarations. With implicit typing, I can just generalize and keep going.

I do recognize that this is a matter of opinion when it comes to readability and that some developers are haunted by the variant in VB6 or are reminded of dynamic typing in Javascript, but there’s really no arguing that this is technically a needless redundancy. For the readability concern, my advice would be to focus on writing code where you don’t need the crutch of specific type reminders inline. For the bad memories of other languages concern, I’d suggest trying to be more idiomatic with languages that you use.

Including Namespace in Declarations

A thing I’ve seen done from time to time is fully qualifying types as return values, parameters, or locals. This usually seems to occur when some automating framework or IDE goody does it for speculative disambiguation in scoping. (In other words, it doesn’t know what namespaces you’ll have so it fully qualifies the type during code generation to minimize the chance of potential namespace collisions.) What’s wrong with that? You’re preemptively avoiding naming problems and making your dependencies very obvious (one might say beating readers over the head with them).

Well, one (such as me) might argue that you could avoid namespace collisions just as easily with good naming conventions and organization and without a DRY violation in your code. If you’re fully scoping all of your types every time you use them, you’re repeating that information everywhere in a file that you use the type when just once with an include/using/import statement at the top would suffice. What happens if you have some very oft-used type in your database and you decide to move it up a level of namespace? A lot more pain if you’ve needlessly repeated that information all over the place. Perhaps enough extra pain to make you live with a bad organization rather than trying to fix it.

Does It Matter?

These all probably seem fairly nit-picky, and I wouldn’t really dispute it for any given instance of one or even for the practices themselves across a codebase. But practices like these are death by a thousand cuts to the maintainability of a code base. The more you work on fast feedback loops, tight development cycles, and getting yourself in the flow of programming, the more that you notice little things like these serving as the record skip in the music of your programming.

When NCrunch has just gone green, I’m entering the refactor portion of red-green-refactor, and I decide to change the type of a variable or the relationship between two types, you know what I don’t want to do? Stop my thought process related to reasoning about code, start wondering if the names of things are in sync with their types, and then do awkward find-alls in the solution to check and make sure I’m keeping duplicate information consistent. I don’t want to do that because it’s an unwelcome and needless context shift. It wastes my time and makes me less efficient.

You don’t go fast by typing fast. You don’t go fast, as Uncle Bob often points out, by making a mess (i.e. deciding not to write tests and clean code). You really don’t go fast by duplicating things. You go fast by eliminating all of the noise in all forms that stands between you and managing the domain concepts, business logic, and dependencies in your application. Redundant variable name changes, type swapping, and namespace declaring are all voices that contribute to that noise that you want to eliminate.

By

How to Make Your Code More Readable

When I was in high school, I had a tendency to procrastinate when it came to assignments and, well, pretty much everything in life. I think that this is sort of a staple of the teenage condition. As a result, I’d often stay up late writing some paper the night before it was due and turn it in.

Working my way through life, I became less of a procrastinator and started to complete tasks on or ahead of schedule and without heroic all-night efforts at the 11th hour. This gave rise to a situation in which I’d frequently have something finished but not turned in for days or even weeks. And I discovered an interesting consequence of this situation–re-reading a paper or presentation with some time had elapsed allowed me to read the paper almost as if someone else had written it. To put it a more computer-science-y way, it nudged me off of the happy path of thinking “of course all of this phrasing makes sense exactly as is, or I wouldn’t have written it.”

Of late, I’ve been steadily working two or three projects and dividing my time up on a per-day basis to still allow myself to get in “the flow.” That is, I spend Monday on project A, Tuesday on project B, Wednesday back on A, and Thursday on C, for instance. The actual number of days and motivation for switching varies, but you get the idea. And like my improved work ethic in school as I grew up, I’ve noticed an interesting consequence: more readable code.

What seems to happen is that I get into a sweet spot between unconscious familiarity and complete lack of insight with the code. Enough time has elapsed since I last looked at it that I don’t simply take it for granted and see without looking, but not enough time has elapsed that I have no idea what’s going on. To illustrate what I mean, consider the following gist (modified from actual code that I was writing for the sake of anonymizing):

public class SomeClass
{
    private readonly List _cusotomers = new List();

    public void AddToQueue(CustomerModel cm)
    {
        if (cm.IsActive && !_cusotomers.Any(c => c.Name == cm.Name))
            _cusotomers.Add(new Customer() { Name = cm.Name });
    }
}

As I write code these days, I rely increasingly on various refactorings during the course of TDD: extract method, extract local variable, add to new class, declare type, etc. In this case, during a refactor cycle, I had extracted the method “AddToQueue” from another method where the “CustomerModel” argument had been a very tightly scoped local variable, such as the “c” variable in the “Any()” call. The result is a method that’s nicely short in scope, but suffers from some naming and semantics that tend to hide a bit about what this method is actually doing. If I’m going to put my money where my mouth is in my various posts deriding comments, I need to do better when it comes to making code self-documenting.

What could be improved here? Well, for starters, the name of the method is a little misleading since the result isn’t always an add. Secondly, what is “cm”? And, if you’ll notice, there’s a typo in the “customers” field–not particularly important, but sloppy. In short, this could use a bit of tightening up–a bit of editing for readability, if you will. How about this:

public class SomeClass
{
    private readonly List _customers = new List();

    public void AddCustomerForModelIfValid(CustomerModel modelOfCustomer)
    {
        if (IsModelValidForAdding(modelOfCustomer))
            AddCustomerForModel(modelOfCustomer);
    }

    private bool IsModelValidForAdding(CustomerModel modelOfCustomer)
    {
        return modelOfCustomer.IsActive && !_customers.Any(c => c.Name == modelOfCustomer.Name);
    }

    private void AddCustomerForModel(CustomerModel modelOfCustomer)
    {
        var customerBasedOnModel = new Customer()
        {
            Name = modelOfCustomer.Name
        };
        _customers.Add(customerBasedOnModel);
    }
}

I don’t know about you, but I’d say the latter version is a lot clearer. In fact, I think it’s so clear with the naming of variables and methods that adding comments would just be awkward. While the first one wasn’t terrible (it’s hard to be too confusing with methods that short), it definitely left something to be desired in the “self-documenting” category. The latter, I’d say, gets there.

The “sweet spot” that I mentioned earlier is the best time to make that kind of thing happen. It’s a little cumbersome in the middle of a refactoring to stop and say, “okay, let’s focus on naming and spelling.” That’s sure to interrupt your flow. But let that code sit for, say, four to seven days, and then give it another look. If you find yourself mumbling things like “what’s cm… oh, that’s right,” then you can be pretty sure others will mumble that as well, but without the “that’s right.” Don’t let that moment slip away–it’s an opportunity that only happens when you read your code a few days after the fact. Use it to fix the code right then and there when you’re reading for understanding instead of creating. You won’t regret it, and maintainers of your code will thank you.

By

A Group Interview With Some OOP Compilers

I started this as an aside to my post about source files as harmful, but axed it as sort of awkward and too much of a digression. Like a weird sweater that you get for your birthday, though, I couldn’t bring myself to toss it, so I saved it as its own draft. Good thing too because it turns out that my surplus of ready drafts has run dry, and I have nothing else to publish. So, without further ado, please enjoy an admittedly weird bit of Friday humor.

Interviewer:     Thanks for joining me, guys. Today I have with me, in alphabetical order, C# C++ and Java Compilers.
C++ Compiler:     How does a pound come before a plus?
Java Compiler:    (Guffaws)
C# Compiler:     Don’t hate.

Interviewer:     Because it has fewer characters…? Ok, amend that to in no particular order.
C++ Compiler:     That’s better.
Java Compiler:    I was last and I didn’t complain.
C# Compiler:     You’re a good citizen.

Interviewer:     So let’s get right to it. Should methods go above variable declarations or below?
C# Compiler:     It doesn’t matter to me.
Java Compiler:    Me neither.
C++ Compiler:     Same here.

Interviewer:     Okay, but surely you have some preference.
(Pause)
C# Compiler:     I mean, our users seem to get pretty worked up about it, but we really don’t care.

Interviewer:     What about declaring variables all at the beginning of a method or just declaring them where you need them?
Java Compiler:    Up to the user, but I prefer the latter because users that do this have less of a tendency to get angry at me due to their mistakes cropping up at runtime.
C++ Compiler:     Well, I don’t care these days, but that issue has some history for me.
C# Compiler:      History?
C++ Compiler:     Yeah… I don’t care, but my dad gets pretty worked up–
(Muffled voice from the other room): I heard that! You kids with your multi-pass compiling. Back in my day, we only needed one pass to compile and we we liked it!
C# Compiler:     lol…C
C++ Compiler:     Dude, not cool–that’s my dad.

Interviewer:     So what about having multiple classes defined in a single file?
C# Compiler:     Whatever, I don’t care.
Java Compiler:    Not allowed. I don’t like this unless they’re nested or private.
C# Compiler:     That’s pretty anal of you.
Java Compiler:    I have standards, which is probably why my users don’t use awful variable names like lpstr_theThing.
C# Compiler:     Yeah, the kind of standards that are responsible for checked exceptions.
Java Compiler:    Wow, ouch. That was a pretty low blow.
C# Compiler:     I’m sorry, that was uncalled for.

Interviewer:     How about Camel casing versus Pascal casing? Underscores in method names? Underscores in front of fields? How methods and such are ordered?
Java Compiler:    We don’t care about any of those things.
C++ Compiler:     Yeah, as long as you don’t use illegal tokens that would confuse us, we really don’t care what you call things.

Interviewer:     So why do people spend so much time arguing about which way is the right way?
C# Compiler:     I can interpret millions of lines of code, but that’s beyond me.

Interviewer:     Is it possible for those arguments to be productive?
Java Compiler:    No —
C++ Compiler:     Look what they did to poor C#!
C# Compiler:     What’s that supposed to mean?
C++ Compiler:     Regions, that’s what. I mean, dude, really?
Java Compiler:    Yeah, I don’t mean to be rude, but that’s kind of gross.
C# Compiler:     Yeah… I feel like the closet that a kid crams all of his stuff into when he’s supposed to clean his room.

Interviewer:     How so?
C# Compiler:     So I provide a language feature that I thought users would like, and they do. It lets them hide code they don’t want to look at, but I didn’t really anticipate all the consequences of that…

Interviewer:     Meaning what, exactly?
(Pause)
Java Compiler:    (Chuckles)
C# Compiler:     Well, meaning people stuff tons of terrible code into my regions and then point at how nice and clean things look, like the kid with his room. He didn’t clean the room — he just crammed everything in the closet.
C++ Compiler:     I don’t know if I have anything that egregious, but it does seem that we do a lot of weird things and field a lot of weird work-arounds because of the file-based nature of code storage and interaction.

Interviewer: So would you say that the continued use of files as the principle means for storing code is a problem?
C# Compiler: I don’t think it matters how the code is stored, but rather how users interact with it.
Java Compiler: Yeah, I mean the way the actual text of the code is stored is an implementation detail, but it doubles as data and user interface, even in sophisticated IDEs like Eclipse.
C# Compiler: (Snorts)
Java Compiler: Oh, sorry – I forgot that someone here likes to be invoked from IDEs that require no less than 12 gigs of memory.
C++ Compiler: You guys sicken me.

Interviewer: What do you think the future of source code is?
C++ Compiler: Separation of the storage details from the presentation to the user.
Java Compiler: Yeah, we’ve beaten around the bush long enough: syntax highlighting, quick navigation, automated refactoring–
C++ Compiler: Most IDEs and productivity tools do everything they can to hide the fact that you’re editing a file, like MS Word hides the fact that you’re more or less editing text.
C# Compiler: It might get more complicated with certain advanced language features: closures, lambda expressions–
Java Compiler: We’ve got those things too now, buddy. Quit showing off.
C# Compiler: What?
C++ Compiler: Those things don’t make it any more complicated — you just wanted to bring them up.
C# Compiler: They create scoping challenges! If you’re storing hierarchical structures of code elements, that stuff matters!
Java Compiler: Sure there are complexities with all kinds of features, but those aren’t significant barriers to the effort. This really should go forward.

Interviewer: Well, that’s about all of the time that we have, so I’d like to thank our interviewees. For their time. Gentle-compilers, always a pleasure.

By

Improving Readability using Moq

While I’ve been switching a lot of my new projects over to using JustMock, as explained here, I still have plenty of existing projects with Moq, and I still like Moq as a tool. One of the things that I have struggled with in Moq that JustMock provides a nice solution to is the cognitive dissonance that arises when thinking about how to reason about your test doubles.

In some situations, such as when you’re injecting the test doubles into your class under test, you want them to appear as if they were just another run of the mill instance of whatever interface/base you’re passing. But at other times you want to configure the mock, and then you want to think of them as actual mock objects. One solution to that is to use Mock.Get() as I described here. Doing that, you can store a reference to the object as if it were any other object but access it using Mock.Get() when you want to do things to its setup:

[gist id=”4998372″]

That’s all well and good, but, perfectionist that I am, I got really tired of all of that Mock.Get() ceremony. It makes lines pointlessly longer, and I think really detracts from the readability of the test classes. So I borrowed an idea from JustMock with its “Helpers” namespace and created a series of extension methods. Some examples are shown here.

[gist id=”4998277″]

These extension methods allow me to alter my test to look like this:

[gist id=”4998488″]

Now there’s no need to switch context, so to speak, between mock object and simple dependency. You always have a simple dependency that just so happens to have some extension methods that you can use for configuration. No need to keep things around as Mock<T> and call the Object property, and no need for all of the Mock.Get().

Of course, there are caveats. This might already exist somewhere and I’m out of the loop. There might be issues with this that I haven’t yet hit, and there is the debugging indirection. And finally, you could theoretically have namespace collisions, though if you’re making methods called “Setup” and “Verify” on your classes that take expression trees and multiple generic parameters, I’d say you have yourself a corner case there, buddy. But all that aside, hopefully you find this useful–or at least a nudge in a direction toward making your own tests a bit more readable or easy to work with.