AOP

My Intro to AOP with PostSharp

PostSharp LogoOn the last episode of my podcast, I interviewed Matt Groves about Aspect Oriented Programming (AOP). Talking with him inspired me enough to really make a go and spend some time with it to see if I could get comfortable with it. I’m going to try to use PostSharp because I like how it works and because (to be honest) they helped promote that last podcast, and that makes me like their style 😉

As Matt talked about in the podcast, AOP is basically a kind of design pattern. Essentially, you find stuff that is in your code and in a lot of methods, but doesn’t ACTUALLY pertain to the method. Common examples are logging, error handling, cache checks, and parameter checking, to name a few. Once you isolate this code that is basically boilerplate code that is used over and over again throughout your methods, you pull that code out and allow it to exist in only one place.

Frameworks like PostSharp act as post-compilers, so you write your code, add some attributes, and PostSharp will take an extra compiler pass through your code and write the code in for you, as if you had done it yourself. This allows for no additional runtime overhead, as the code works out to just basically be your standard code you would have written anyway.

To get started, head over to PostSharp’s site and download their product. It gets added as a Visual Studio extension and – as of today – you get a 45 day license to their full product when you download it. After that, it will revert to the free version. The free version still has a ton of great features and everything I’m doing today will work on only the free version.

To start with, I’m only going to make a console application that just does some simple string manipulation. You can see the entire project in its completed state on GitHub here.

After I created the project, I had to right click the project and select Add PostSharp to Project. This added a reference to PostSharp’s .dll and set PostSharp up in my packages config. Now, we can start making our first aspect. I’m going to tackle the “low hanging fruit” of some very simple logging first.

I’m going to keep this very simple, so I’m just going to do Console.WriteLines instead of complicating this project by integrating a complicated logging framework just to show an example. I have a Utility class with a ReverseString method. In addition to the “business logic” of actually reversing the string, I am also writing out every entry and exit to and from the method.

public class Utility
    {
        public string ReverseString (string input)
        {
            Console.WriteLine("Entering ReverseString at {0}", DateTime.Now.Ticks.ToString());
            var inputArray = input.ToCharArray();
            Array.Reverse(inputArray);
            Console.WriteLine("Leaving ReverseString at {0}", DateTime.Now.Ticks.ToString());
            return new string(inputArray);            
        }
    }

Calling that method with some test data gives me this output:
Original Results

Now, every method I’d write, I’d have to dirty up with those WriteLines. It clutters up the code and makes it that much harder to understand. Let’s pull that out into an Aspect.

I add a plain C# class to my project called WriteLineAttribute.cs. The code for it is here:

using PostSharp.Aspects;
using System;

namespace IntroToAop1
{
    [Serializable] 
    public class WriteLineAttribute : OnMethodBoundaryAspect 
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("Entering {0} at {1}", args.Method.Name, DateTime.Now.Ticks.ToString());
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            Console.WriteLine("Leaving {0} at {1}", args.Method.Name, DateTime.Now.Ticks.ToString());
        } 
    }
}

Some things to point out. You have to mark the class as Serializable. This is just due to how PostSharp manages these things. Secondly, you just have to inherit from OnMethodBoundaryAspect. That is one of the built in Aspects that PostSharp offers for exactly what we want to do, operating coming in and out of methods. Now, to get my behavior, I just override the OnEntry and OnExit methods and put the Console.WriteLines in that I had before (making the method name dynamically generated from the arguments passed in to me).

Now, my ReverseString method looks like this:

[WriteLine]
public string ReverseString (string input)
{
    var inputArray = input.ToCharArray();
    Array.Reverse(inputArray);
    return new string(inputArray);            
}

The WriteLines are gone and I just added the [WriteLine] attribute at the top of my method. Running that gives me this output:
After Results

Okay, maybe this intro isn’t “blow your mind impressive”, but it does show you some of the power to make clean code that PostSharp offers you. If I wanted to log something new, I only have to change it in one place. If I wanted to make that logging come on and off based on a compile flag or a configuration value, again it is a single point of change. And the fact that my results are exactly the same (except for the timestamps) means that I had a successful refactor while cleaning up my code.

Again, if you want to play around with the code, you can find it on GitHub. I’ve added some more string manipulation methods just to further show how much nicer the code will look “PostSharp’ed”.

Next time, I’m going to use PostSharp to validate the parameters on my methods so that they don’t blow up when you pass in null values!

Podcasts

Aspect Oriented Programming with Matthew Groves

Matt Groves, Pete On Software Podcast Interview Victim OneI’ve been moving right along with my podcast this past month. My first episode was published on December 29, 2013 and as of today, January 29, 2014 I’ve published five episodes. The fifth one, which I just published is my very first episode with an interview.

If you’ve listened to my podcast intro, you know that talking to and about the people in our industry has been a goal right from the start. That being said, I wanted to see if I could make shows by myself at first to see if I was really going to do this thing. From now on, I plan to mix up the kinds of shows as I find the right topics or guests to suit one style or the other.

In Episode 5, I knew from the start that I wanted to have a guest. Like a lot of podcasters, I planned on using the guests in a very selfish way. Sure, I’d be making the podcasts for the listeners, but at the same time I wanted to pull double duty and learn about things that I’ve always been curious about.

As I thought about topics to discuss, the first one that jumped out at me was Aspect Oriented Programming. I kind of knew what it was about, but I really wanted to know and understand more. As soon as I finished recording Episode 4 of the podcast, I used my podcast endorphins to take a risk and send out an email to the guy who literally wrote the book on Aspect Oriented Programming.

Matt was gracious enough to give me some time and talk about the topic, some of the frameworks you’ll encounter, and his book. He even provided a promo code for my listeners, so I couldn’t have been happier with him as a guest. He made it very easy to talk about this topic and he really knows the landscape. Check out the episode and definitely use the promo code to buy the book if your interest is piqued by the discussion.

I also learned a few tips and tricks that I’ll have to put into play next time when recording and mixing two disparate tracks and I’m thankful for the opportunity to get to keep doing this, to keep learning and trying to get better, and to work in a community where people like Matt are who are so willing to come and make time for a lowly podcast with literally TENS of listeners per episode.

Great big thanks again to Matt and to all of you who listen to the show.

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

Podcasts

The Hardest Part of Podcasting (so far)

Podcaster..(not actually me ;) )The most difficult thing that I’ve found while doing my podcast is the whole “talking to no one” part. I already know that I talk very quickly, especially when I’m excited. I also now know from editing my podcasts that I tend to be sloppy in my pronunciation of a LOT of words. I’ve definitely been more focused on that.

What is getting me is being able to “fake” the vocal dynamics that happen as you are interacting with another human. Normally, you’d feed off their interactions and subtle non-verbal cues, but instead I feel like I’m an actor reciting an ad-hoc soliloquy and currently I’m just not that talented. I’m balancing that fine line between speaking at a good pace, speaking clearly and enunciating, and speaking with vocal dynamics that don’t sound fake and forced.

I’ve been trying to think of some good ways to “fake” this. One idea is maybe put a mirror in front of me and talk to the “other person” who is there. Another idea is to make my son or my wife sit there near by and I’ll talk to them. I do plan on having some interview subjects on soon, so those kinds of episodes won’t be an issue. I’m just more concerned and focused about my “verbal essay” (rant) style episodes.

Does anyone have any good practical tips that they’ve used when “performing for no one”?

Mentoring

On Helping Other People

Life PreserverA very common objection that I hear that keeps people from teaching others is that the person feels that they aren’t “expert” enough to teach someone else. Any while I don’t doubt that the person lacks the credentials to be an “expert”, they do have some life experience to share.

The way I heard it described the other day on The Podcast Answer Man (link to episode) was that it is more about where each person is in their life. As an adult, I don’t see a 6th grader as having a wealth of knowledge. However, to a 4th grader, the 6th grader has a lot of valuable answers and experience to share.

All of you have at least a “6th grade level knowledge” about something. Go out and be a hero to someone who is at that 5th grade level or below. As long as you are honest about where you’re at and what your story is, you aren’t a fraud or a phony. Everyone is a beginner at some point. There is nothing wrong with an “advanced beginner” or higher turning around and helping those on the trail behind them.

Excuses are a crutch. If you feel compelled to help others, just do it. Start a blog, start a podcast, speak at user groups… whatever gets you excited. Your content won’t be for everyone, but – NEWS FLASH – no content pleases everyone. If someone is too advanced for your content, then they aren’t in your core audience. As long as you didn’t promise an advanced session, don’t worry about it.

Now go create!

Podcasts

Podcast Episode 2 is Live: Staying Current

BraggingMy second podcast went out this weekend.

There is one section when I am talking about my own answer to “How do you stay current?” and I agonized back and forth a bit as to whether to leave it all in. The point was that I’m busy just like everyone else is busy, I still make time for everything that I do to stay current. I hope that it doesn’t come off as bragging or humble bragging or that I’m just a gigantic jerk. I wanted to really bring home the point that I go on to quote in the show that I once heard Leon Gersing make at the M3 conference that, “If you say you don’t have time for something, you don’t”.

I heard him say that at the lunchtime keynote and it really hit me about how much I had been slacking at that point. So, I cut out some useless TV and I was able to do everything else in my life and still spend several hours a week honing my craft.

As I said, I’m hoping that it comes off more as a way to shift priorities around to create a plan rather than “Hey, look at me, I’m perfect”.

That all being said, I’m off to CodeMash this week for my yearly dose of inspiration and to remind myself just how many smart people are out there and how much I don’t know!

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.