Joe White’s Blog

Life, .NET, and Cats


Archive for the ‘Cats’ Category

TechEd notes: 10 Ways To Improve Your Code

Tuesday, June 3rd, 2008

10 Ways To Improve Your Code
Neal Ford
Sr. Software Architect / Meme Wrangler
ThoughtWorks

Where did this topic come from?
Book: “The Productive Programmer”, Neal Ford
Exists in two parts, “mechanics” and “practices”.
Mechanics: how to speed you up, learning keyboard shortcuts.
Today is more Practical (and philosophical).

“The unexamined life is not worth living.” — Socrates

“Unexamined code isn’t worth executing.” — Neal, stealing from Socrates

1. Test driven design.

When you’re really rigorous at test-driven development, it has effects on your design. You’re creating the first consumer of your code.

  • Consumption awareness. You’re aware of how the rest of the world will use the code, before they use it.
  • Mocking of dependent objects. If you’re really unit testing, you’re mocking out the dependencies, which forces you to think about the collaboration between these objects.
  • Introverted vs. extroverted objects:
    • If you do TDD, you’ll learn to avoid “extroverted objects” that reach out to create other objects, fire constructors, allocate resources, etc.
    • Instead, you’ll use “introverted objects” where all dependencies are injected via parameters, properties, etc. You tend to move object creation to a few simple places, and can use things like real dependency injection. Also called “shy objects”.

2. Metrics and static analysis.

Compilation is a really, really weak form of unit testing. You can compile any sort of trash. “It compiles” doesn’t tell you much.

Source Monitor (can do many languages including C# and Delphi). Lots of metrics, including cyclomatic complexity. Can set thresholds and have it show the outliers. Has both GUI and command line. Costs you virtually nothing, and will help you find problem spots.

Cyclomatic complexity (1978): measure the complexity of your code. Has to do with the number of paths through the code, though it’s not quite that simple; it’s based on number of branches and decisions. But higher cyclomatic complexity tends to correlate to more bugs.

FxCop.

3. Good Citizenship.

Cooperation with the rest of the world.

Properties != Encapsulation.

  • See too many devs who use a tool to spit out public read/write properties for every one of their fields, and then engage their brain.
  • “Knee-jerk propertiation.”
  • Much better off passing values to a setter method like SetAddress, which means you can’t be a bad citizen by e.g. setting City without setting State — your object should go atomically from one good state to another good state.
  • Objects are the keepers of state, and they should guard that jealously.
  • Only create properties when you need to call them from real code.

Constructors

  • Specific contract for how to create valid objects.
  • How often is a valid object blank? (from a business standpoint) … Never!
  • Don’t provide default constructors for domain objects.
  • Push back on frameworks that try to require this
  • If you need a null object (and have a language that requires you to have a stateful object to say you have no state)…

Static methods

  • Should be a black box
  • You never worry, when you call the sqrt function, that the next time you call it it’s going to give you the cube root.
  • Statics should be non-stateful.
  • Where you get problems is when you mix statics with state.

Mixing static + state

  • The Evil Singleton Pattern
  • Bad because
    • Mixes responsibilities (doing stuff and maintaining its instance)
    • Untestable
    • Object version of global variables
  • Better: object and factory, where the factory handles the instantiation policing
    • Factory can even call object’s private constructor through reflection. Then you’re enforcing that nobody can instantiate the singleton accidentally.

4. YAGNI

Picture of gold-plated toilet

Discourage gold-plating.

  • Build simplest thing we need right now!
  • No speculative development. Speculative development:
    • Increases software entropy. The more code, the more complexity, even if you aren’t using it.
    • Only saves time if you can guarantee you won’t have to change it later
    • Leads to frameworks.
      • Frameworks are not inherently bad, but we have framework-itis.
      • Let’s face it, building a framework is cooler than what you should be doing right now.
      • Frameworks are written by people engaged in ivory-tower building.
      • The best frameworks are not created by somebody who wants to build a framework. The best are extracted from working code.

Changeability. Code with anticipatory design is larger and harder to refactor and maintain.

5. Shaving with Occam

Sir William of Occam: “Given multiple explanations, the simplest is best.”

Simplest is really hard to come by.

Dave Thomas was brought in to solve problem with volume of internal mail. Inter-office memos were constantly getting misrouted. So they brought in an OCR machine, and brought Dave in to write software for this thing. At one point, Dave said, “Couldn’t you solve this problem with colored envelopes?”

It’s really hard to understand the essence of the problem and address that.

We are drowning in complexity.

  • Essential complexity: We have a hard problem that we’re trying to solve.
  • Accidental complexity: We’ve made the problem hard.

The Goal

  • Simplify essential complexity
  • Kill accidental complexity

This also affects the kind of tools you use. E.g., “static” vs. “dynamic” languages. (I already noted this “ essence vs. ceremony“.) Something nasty and multithreaded would be better written in something like F#.

Interlude: the Top Ten Corporate Code Smells

  1. We invented our own web / persistence / messaging / caching / logging framework because none of the existing ones was good enough.
  2. We bought the entire tool suite (even though we only needed about 10% of it) because it was cheaper than buying the individual tools.
  3. We use BizTalk because… (I always stop listening at this point) Okay, it has some legitimate uses, but it’s been much abused.
  4. We can’t use any open source code because our lawyers say we can’t.
  5. We have an Architect (note the capital A) who reviews all code pre-checkin and decides whether or not to allow it into version control. (New feature in VSTS.)
  6. The only XmlDoc is the default message explaining how to change your default XmlDoc template.
  7. We keep all of our business logic in stored procedures… for performance reasons. There is some tortured logic at work here, but that ignores that dealing with stored procs will slow down your development. Let’s have a talk about premature optimization.
  8. We don’t have time to write unit tests — we’re spending too much time debugging.
  9. The initial estimate must be within 15% of the final cost, the post-analysis estimate must be within 10%, and the post-design estimate must be within 5%. (Punished for coming in too low as well as for coming in too high. The team will overestimate on purpose, get done early, not tell you about it, twiddle their thumbs until they hit the golden window, and then say, “Okay, all done!”)
  10. Blue Screen of Death.

Side note: Unless you work for NASA, your problem isn’t harder than everyone else’s. You’re just doing it wrong.

6. Question authority.

Dave Thomas’ story of angry monkeys. (The story of the stepladder, the bananas, and the ice water. “That’s the way we’ve always done it.”)

[Test]
public void UpdateCacheAndVerifyThatItemExists()

Long camel-cased names are hard to read, and test names tend to be long. Neal’s suggestion: use underscores just for test names.

[Test]
public void Update_cache_and_verify_that_item_exists()

Fluent interface:

ICar car = Car.describedAs()
              .Box
              .Insulated
              .Includes(Equipment.Ladder)
              .Has(Lining.Cork);

instead of setting lots of properties, to make it more readable for non-programmers. Thing is, it violates the rules of properties, by making a property getter (Box) that mutates the object. But in the context, it makes for much clearer code.

Killing I

  • Interfaces define semantic intent
  • No implementation details…
  • …except in the name!
  • Don’t name interfaces with a leading “I”
  • Name concrete classes with a naming pattern
  • (I’m not sure that I would agree with Neal on this, but it’s worth thinking about)

What’s Bad About Standards?

  • Forces you to create default constructors
  • Property setters return void
  • Can’t use PONOs for fluent interfaces

Non-intuitive

  • Pair programming (seems like it would be 50% slower, but in reality, once you settle into it, you develop 15% slower, but have 50% fewer defects)

Read AntiPatterns.

  • GiveMeEstimatesNow. Presented with a problem, asked for an estimate out of the blue; you don’t know anything about it, but the boss asks for a guess. That becomes an ironclad contract.
  • StandingOnTheShouldersOfMidgets. Have a disastrous tool or framework that you’re required to use in every application, because it’s a corporate standard.

Anti-patterns are the lore of software. Take advantage of this prior art. Don’t think that the problems at your job are uniquely yours.

7. Composed Method.

“Smalltalk Best Practice Patterns” by Kent Beck. Smalltalk people were some of the first OO programmers, and came up with elegant solutions. (They’ve got a head start on the rest of us.)

  • Every public method consists of steps implemented as private methods.
  • You can tell something’s wrong with the existing code if there have to be comments.
  • Extract methods.
  • Find opportunities for code reuse. Some of those methods you extract might start to look like Template Methods, which opens up more opportunities.

8. Polyglot Programming

Leveraging existing platforms with languages targeted at specific problems and applications

We have lots of .NET languages. Why not take advantage of them, rather than thinking there’s a framework for everything that you can use from the One True Language?

Looming problems / opportunities

  • Massively parallel processing (multithreading)
    • Use a functional language: F#, Haskell.net
  • Schedule pressure
    • Use a dynamic language: IronPython, IronRuby
    • Use an alternate Web framework: Django, Ruby on Rails
  • New approaches
    • Domain-specific languages (DSLs)
    • Fluent Interfaces

Write your multithreaded logic in F#, your GUI in C# or VB.NET, your unit tests in IronPython or IronRuby, and use DSLs

  • Wouldn’t that add complexity?
  • In the past, language == platform
  • Now, language != platform

Ola’s Pyramid

  • Stable language at the bottom, e.g. C#. Static-typed, statically-verified. Maybe even stricter than C#, like a mathematical language.
  • Above that, a dynamic (non-ceremonial, e.g. F#) language that lets you write code quickly.
  • Above that, a DSL that gets you closer to the problem domain.

9. Learn Every Nuance

  • Reflection
  • Regexes
  • Dependency injection
  • Closures
  • Lambda expressions
  • Extension classes
  • And once you’ve learned it, teach it to your co-workers. E.g., regular expressions.
  • Can save you orders of magnitude of work.

10. Anti-objects

Comes from OOPSLA paper called “Collaborative Diffusion”.

“The metaphor of objects can go too far by making us try to create objects that are too much inspired by the real world.”

Figure vs. ground. Sometimes you need to see the problem a different way.

Pac-Man console had less memory than a 10-year-old cell phone. Problem to solve for the ghosts: What is the shortest distance between two moving objects in a maze? Solution: don’t model the ghost; model the maze. Intelligence was built into the maze itself. Each cell had state. Invented “Pac-Man smell”. A cell he just moved off of had “maximum smell - 1″, and it decayed quickly. Ghosts just had to smell Pac-Man. The ghosts wander randomly until they pick up the scent, and then they move into the cell with higher smell. So they will never cut him off at the pass (on purpose)… but it was a very simple and memory-efficient solution.

Healthy cats

Sunday, April 8th, 2007

All four cats are home. We got to bring Tycho home from the vet on Friday, and Goober yesterday. (Tycho was so ready to go home. I could almost hear him saying, “Give me the keys! I’ll drive!”)

All four cats’ values are back down to well within the normal range — even Goober’s, which started out so far off the charts, less than a week ago, that we had no idea whether he was going to survive. He is all better. (There may be long-term effects, five or ten or fifteen years down the road. But that’s no worse than some of the other health problems our cats have turned up with; in my mind, that’s as good as healthy.)

They all get re-checked on Wednesday, and then at progressively longer intervals thereafter.

Life is much better.

Well, mostly better. Now we’ve got to give them subcutaneous fluids every day. That means that we (not, repeat, not trained professionals) stick an IV needle into each cat’s back, and then try to get them to sit still and not flinch for five or ten minutes. (I used to donate plasma, and at the end of the process, they would run fluids back into the IV to replace what they took. That stuff was freaking cold. So I know how the cats feel. But it’s still gotta be done if we’re going to make sure they stay healthy.)

We try to remind them that it’s either five or ten minutes a day of something they don’t like, or twenty-four hours a day of being at the vet. They don’t seem convinced.

Ah well. Band-Aids are cheap.

Two cats home

Thursday, April 5th, 2007

Stefan and Noel got to come home today.

All four cats are doing really well. The intravenous fluids have been working very well on all of them. Hopefully the same will end up being true for everyone else’s cats who had been eating m/d and are now stuck in the hospital.

We’ll have to give Stefan and Noel subcutaneous fluids once a day for a while (the doctor wasn’t there when we visited, so we’ll have to wait till tomorrow to find out how long this arrangement will last). This basically amounts to attaching an IV needle to a bag of saline solution, sticking the needle in the scruff of their neck, and getting them to sit still for ten minutes or so. It’s not really as bad as it sounds. They showed us how to do it before we brought them home. Both cats put up with it a lot better than I thought they would; it didn’t seem to hurt them at all. They just didn’t want to sit still that long.

The other two cats will be at the vet a while longer. Tycho’s blood-test values were normal when they checked him today, but they’re keeping him another day or so just to make sure, since his values were high when we brought him in. Goober probably won’t be able to come home until Saturday at the absolute earliest, maybe Monday.

Jennie brought a milk ring along when we went to visit Goober this morning, and he was playing with it enthusiastically. He’s back to himself.

I’m not sure what to think about Tycho. He’s been friendly. To the lab techs. At the vet’s office. This is not like him. He even let one of the doctors scratch him on the nose, and he didn’t try to bite or anything. Jennie and I have started calling him “pod-cat”. It’s not that we mind him being nice at the vet’s office. Usually they have to sedate him to do anything to him at all, and they have to get out the metal-studded elbow-length heavy-duty leather gloves to be able to hold him long enough to sedate him. So it’s not that we mind not having to deal with that. It’s just that, well, to quote an old Garfield comic strip (which ended with Garfield in a straitjacket in a padded room), “People don’t want nice… people want consistency.”

Goober doesn’t seem to mind being at the vet’s office too much — he’s enough back to his usual autistic self that I’m not entirely convinced that he even notices where he is. But Tycho is desperate to come home. He’s being (unusually) nice and all, but sounded so pitiful when we left this evening. He just about smashed my fingers against the cage bars when he head-butted my hand.

I really hope everything looks good again tomorrow so he can come home. I guess I’m just a sucker for a sad yowl.

Cat recall

Tuesday, April 3rd, 2007

All four of our cats are in the hospital now.

Jennie took Stefan, Tycho, and Noel to the vet this afternoon to be checked, since they’ve all been eating the same (recalled) food. All of their blood tests came back with high levels of bad stuff. Nowhere near as high as Goober’s, and their kidneys didn’t appear to be swollen, but the levels still well above the upper bound of the “good” range. So they’re all on IV fluids for 48 hours to try to flush it out of their systems too.

It’s going to be weird being in a house with no cats. They’ll re-test Goober tomorrow night, but he’ll probably be in the hospital for a few more days after that.

On the plus side, he did pee a couple of times today, so his kidneys are pulling at least some of their weight. It’s too soon to know much more.

Goober and the cat-food recall

Monday, April 2nd, 2007

Until I took Goober to the vet tonight, I didn’t know that the pet-food recall had expanded to a second manufacturer.

Now I do. Hills Veterinary Diet m/d formula — the food that all four of our cats eat.

(Well, did eat. They sure as hell don’t anymore.)

Goober hadn’t been himself for a few days. He wasn’t interested in playing, and he had thrown up a few times, both of which are extremely unusual for him.

He’s still at the vet. His kidneys are enlarged, and a couple of the counts from his blood tests were about 10x what they should be (I’m not sure of details — I was in no frame of mind to be taking notes). They’re treating it as acute renal failure: they’re putting him on intravenous fluids, to flush the bad stuff out of his system.

He’ll be in the hospital for 48 hours (during which we can visit him as often as we like), and then they’ll do the blood tests again. All we can do is wait, and hope. And bring the other three cats in so we can get them checked too. And be glad that we hadn’t spent any of our tax refund yet. And pick up some different cat food in the morning — at a different vet’s office. Our vet’s office is sold out of the alternative they’re recommending.

(Apparently the vet’s office had called us to warn us of the recall, but they called Jennie’s cell phone, which I had taken out of town with me this weekend. Since I have no clue how to check her voicemail and I didn’t get back until today, we hadn’t gotten the news. Maybe this is a compelling reason to drop the land line, and finally get me a cell phone.)

Getting to sleep tonight will be an interesting challenge. So will focusing on work tomorrow. Wish me — and especially Goober — luck.

General preference: keep the cat dry

Tuesday, May 31st, 2005

I was supposed to take Tycho to the vet this evening, for another re-check on his eye. But after driving home from work, I decided against it. It’s raining a bit (sarcasm), and I decided I didn’t really want to drive my crabbiest child to the vet, during a thunderstorm, through 84th Street Lake.

Our regular vet will be in Thursday morning; we’ll go then. (hastily checks weather forecast) Yeah, we’ll go then.

Anniversary gift: mostly healthy cat

Wednesday, May 11th, 2005

Two very good things happened yesterday.

One: we took Tycho back to the vet for a re-check, and she said that his eye looked “90% better”. She doesn’t think we’re going to need to take him to a specialist at this point (which saves us a five-hour car trip — each way — with a yowling cat in tow), so that was a relief. If the thing in his eye had been a tumor, she told us, then we wouldn’t have seen this kind of improvement with the meds we had him on. (She called us after we got home, with the lab results from his first visit, and there were indeed no cancerous cells. Hooray!) Not only is his eye doing better, but now we only have to put ointment in his eye four times a day, instead of six — much more manageable, given our work schedules. He goes back in a week for another re-check.

Two: yesterday was our eight-year anniversary. (Our anniversary celebration consisted of taking Tycho to the vet. See, we still know how to party till it hurts.)

Tycho goes to the eye doctor

Friday, May 6th, 2005

Well, the specialist was a bust.

We took Tycho in to see the eye specialist this morning. We had already called ahead, and warned them that Tycho was difficult and would need sleepy gas before they could examine him. We had an appointment of sorts — they’d said to bring him in anytime between 7:00 and 9:00, the earlier the better.

We arrived at 7:30, told them our name, filled out the little new-patient information sheet, and waited. Tycho made some noise in the car on the way there, but once we got into the waiting room, he was really quiet. After a while, they let us into a waiting room, which is when he decided that yeah, this really was the vet, and started hissing. We opened both doors on his cat carrier, but he declined to come out, and crouched there, hissing every now and then, tail lashing.

More waiting, and eventually the doctor came in. We did introductions all around, and explained again, as we had when we called in originally, that they’d need to put him under before they examined him. The doctor went to look at Tycho, who hissed. And the doctor flinched back, very visibly. Tycho was still being pretty mild — he wasn’t even yowling yet, like he usually does at the vet.

Then the doctor told us that we didn’t have a surgical appointment, so he couldn’t see Tycho today and we’d have to bring him back. We were a little bewildered by this, and explained that we did have an appointment. At which point the doctor said that he “didn’t really appreciate working on cats like this”, said we’d have to go somewhere else, and left the room.

This is crazy. Our regular vet would never think of refusing to treat a cat just because of the cat’s attitude. In fact, they’ve assured us they have much worse patients than Tycho. Jennie was so furious she was in tears, and I’m not too happy myself. It’s obvious that not all the fault goes with the doctor — his staff obviously didn’t pass along the message we left about Tycho being temperamental — but whatever the case, we were treated pretty poorly. And we still don’t know what’s wrong with Tycho’s eye, or how bad it was, or what’s going to happen next.

We can’t even get hold of our regular vet. She had to leave the office, because she got bitten by a dog this morning. I think there’s some kind of message there, but I’m not quite sure what it is.

It’s a pretty crappy turn of events, and we’re stuck worrying. We’ll get Tycho taken care of, one way or another; there are doctors out there who actually love animals and want to help. We may have to go on a road trip, which would be just joyous with a yowling beanlet in the back seat, but one way or another, we’ll make sure he’s okay.

He is himself again, I’m happy to report. He was pretty sluggish for about a day after his last vet visit, but he’s back to normal, struggling when we try to medicate him, and tearing around the house at the speed of beanlet. We’ve got our bitty back. We just want to know what we need to do to keep him okay. And because this doctor was scared of cats, or something, we still don’t know that.

Tycho’s eye problems

Tuesday, May 3rd, 2005

Last night, Jennie noticed some icky-looking stuff on Tycho’s eye. A thin line of whitish stuff on the outside of his eye, right next to the eyelid. At first, I thought it might have been mucus or something (he’s been sneezing a lot lately), but in any case, it worried us enough that Jennie took Tycho to the vet this morning. As always, that was a major production; they had to put Tycho in the sleepy-gas box so the vet could even examine him (as always).

Result of that visit: we still don’t know what’s wrong (pretty normal, for our cats), but we have an appointment for Tycho to see an eye specialist on Friday (not normal — first time any of our cats has needed to see any kind of specialist). The vet said it’s possible that it’s a tumor. It might also be just a scratch, or something like that, but she thinks his eye would be watering more, and he’d be showing a lot more pain, if that were the case. Or, knowing our cats, it might be something completely different. His eyelids are puffy enough that I’m guessing at some kind of infection rather than a tumor, but… well, I’m hardly the expert here. We’re keeping our fingers crossed — all we can really do, for now.

Well, that, and giving him the two different kinds of eye ointment the vet gave us; we’re hoping that they’ll even make his eye a little better by Friday, but we’ll just have to see. Both ointments have to be squirted directly into his eye, and both are a gel-like consistency (oh, for the days of good old liquid eyedrops). One has to be put in twice a day, and the other is four times a day, and we can’t give them both to him at the same time — we have to give him the four-times-a-day one, wait at least five minutes, and then give him the twice-a-day one, if we can still find him by the time the five minutes have passed.

Thing is, he hasn’t been running away when we go to get him, or struggling too much when we hold him down and put stuff in his eye. I don’t know if he’s subdued (or exhausted) from the trip to the vet and the aftereffects of the anaesthesia, or if he’s in too much pain to put up much fight, or if the stuff actually makes his eye feel enough better that he’s willing to put up with it for now. In any case, he’s certainly not acting like his usual self, and I’m worried about my bitty.

Sigh. Holding out for Friday. (We could’ve gotten him into the specialist earlier than that, if we hadn’t known for a fact that he’d need to be tranquilized for the experience; that wound up dictating the schedule slot.)

Wish him luck. Poor beanlet.

Life’s little mystery #74,512: Scented cat litter

Wednesday, April 20th, 2005

So what’s the idea behind cat litter with perfume in it? I picked some up by mistake months ago, and still have most of it left, ’cause it makes the litterbox smell worse than before I changed it. Maybe it’s just me, but I don’t really want my cats’ butts to smell like some little old lady’s idea of appropriate (cough) fragrance (wheeze) for Sunday morning Baptist church service (gag). Thanks, but no thanks.


Joe White's Blog copyright © 2004-2008. Portions of the site layout use Yahoo! YUI Reset, Fonts, and Grids.
Proudly powered by WordPress. Entries (RSS) and Comments (RSS).