Tips

Hack Your TODO List With Google Keep

Hack Your TODO List With Google Keep

Trying To Keep It Alllll Together…

I’m a big fan of TODO lists. I find that they’re a great way for me to set up a bunch of tasks and feel really productive as I work through them. I’ll make TODO lists for almost anything. What do I need to get done tomorrow morning at work? What groceries do I need to get? What topics am I thinking of blogging about? I’ll get some sort of TODO list going for anything.

The one thing that I need in my TODO list to stay effective is to constantly have it around me to remind me. I was running the Evernote app on my Android phone and recently made the observation that things that I put in there had a much higher likelihood of getting done versus things I put in my work notebook. The reason? I check my phone a lot more than my work notebook. I have my phone with me when I grocery shop. I have it before and after I workout at the gym. It’s my alarm in the morning so I have access to it as soon as I wake up. My work notebook? Not so much.

The problem here is that my important work tasks I want to accomplish were not getting the same treatment my out-of-work tasks were getting. They weren’t getting the same success rate.

Enter Google Keep

I try to meet up with my teammates once a month to discuss their goals or things we need to work through at the office. In my last round of one-on-ones, I was discussing my TODO lists with one of my colleagues, Samantha. She said that she noticed I was using Evernote, but was curious of I’ve ever tried out Google Keep. I admitted that I hadn’t, but she was speaking highly of it. “Why not give it a shot?” I¬†thought. But it hacked my TODO list concept in a big way.

Google Keep has one feature that I think is totally awesome on my phone. I never tried this with Evernote, so I’m not claiming that it can’t do this. The phone widget is truly awesome. Right on my homescreen of my phone, I can see my TODO lists. This takes that first point I was discussing (need to have access to it all the time) to a whole new level. Now instead of having to go to the app itself to get refreshed on what I need to do, almost any time I touch my phone I’m having visibility into my TODO lists.

A second powerful feature is the idea of checkboxes for progress. This probably sounds like it’s not all that important. “Google Keep has checkboxes? Great… I have bullet points in any other app I can get my hands on!” I can hear you saying that now ūüėČ But it’s different. I was using Evernote and keeping bulleted lists, and when I was through with something, I’d just delete the whole bullet point. The idea of checking things off your list is powerful because it shows you that your making progress. I can see that I have only 3 of 10 items left on my list and that gives me a bit more drive to try and knock off the rest. If my list is always just a view of what’s left, it will always feel like it’s never done.

Summary

I’m not trying to push Google Keep or bash Evernote here… I’m just trying to show you how a few simple hacks¬†in my TODO lists were able to provide some real positive benefits. For me, the things I need in my TODO list technology are:

  • Easy to access
  • Ability to access frequently
  • Insight into progress I’m making on the list
  • …¬†Not cost me a cent!

Your list might look a bit different. You could argue that you don’t always want the list in front of you or that you don’t want total transparency into the progress you’re making. I can’t speak for you in terms of what will be most effective, but I highly recommend Google Keep after using it for only a couple of weeks.

Now my only problem is that I look like I’m ignoring people if I’m taking notes on my phone in a meeting! Thanks for the suggestion, Sam!


Refactoring For Interfaces: An Adventure From The Trenches

puzzle

Refactoring: Some Background

If you’re a seasoned programmer you know all about refactoring. If you’re relatively new to programming, you probably have heard of refactoring but don’t have that much experience actually doing it. After all, it’s easier to just rewrite things from scratch instead of trying to make a huge design change part way through, right? In any mature software project, it’s often the case where you’ll get to a point where your code base in its current state cannot properly sustain large changes going forward. It’s not really anyone’s fault–it’s totally natural. It’s impossible to plan absolutely everything that comes up, so it’s probable that at some point at least part of your software project will face refactoring.

In my real life example, I was tasked with refactoring a software project that has a single owner. I’m close with the owner and they’re a very technical person, but they’re also not a programmer. Because I’m not physically near the owner (and I have a full-time job, among other things I’m doing) it’s often difficult to debug any problems that come up. The owner can’t simply open an editor and get down to the code to fix things up.

So there was an obvious solution which I avoided in the first place… Unit tests. Duh. I need unit tests. So that’s an easy solution right? I’ll bust out my favourite testing framework (I’m a fan of xUnit) and start getting some solid code coverage. Well… in an ideal world, like every programming article is ever written, this would have been the case. But that wasn’t the case. My software project does a lot of direct HTTP/FTP requests and interacts with particular hardware on the machine. How awesome is writing a unit test that contacts an HTTP server? Not very awesome.

What was I to do? I need to be able to write unit tests so that I can validate my software before putting it in my customer’s hands, but I can’t test it with unit tests because I don’t have the hardware!

Refactoring for Interfaces

Okay, so the first step in my master plan is to refactor for interfaces. What do I mean by that? Well, I have a lot of code that will call out and make HTTP requests and it has a specific dependency on System.Net.WebRequest. The same thing holds true for my FTP requests I want to make. Because I have that dependency within my classes, it means I have no choice but to call out to the network and go do these things.

I could design it a different way though. What if I abstracted the web requests away so that I didn’t actually have to call that class directly? What if I could have a reference to some instance that met some API that would just do that stuff for me? I mean, my class knows all about it’s on particular job, but it truthfully doesn’t know the first thing about calling out to the Internet to go post some HTTP requests. This means if someone else is responsible for providing me with a mechanism for giving me the ability to post HTTP requests, this other entity could also fool me and not actually send out HTTP requests at all! That sounds like exactly what my test framework would want to do.

My first step was to look at the properties and methods I was using on the WebRequest class. What was shared between the HTTP and FTP requests that I was creating? The few things I had to consider were:

  • Some sort of Send() method to actually send the request
  • A URI to identify where the request is¬†being sent
  • A timeout property

I then created an interface for a web request that had these properties/methods accessible and created some wrapper classes that implemented this interface but encapsulated the functionality of the underlying web requests. The next step was creating a class and interface for a “factory” that could create these requests. This is because my code that needs to make HTTP/FTP requests only knows it needs to make those requests–It doesn’t have any knowledge on how to actually create one.

With my interfaces for my requests and my factory that creates them, I was able to move onto the next step.

Create Mocks for the Interfaces

Now that I had my classes leveraging interfaces instead of concrete classes internally, I could mock the inner-workings of my classes. This would provide two major benefits:

  • I could create tests that wouldn’t have to actually go out to the Internet/network.
  • I could create instrumented mocks that would let me test whether certain web requests were being made.

I started off my writing up some unit tests. I tried to get as much code coverage as I could by doing simple tests (i.e. create an object, check default values, call a method and check a result, etc…). Once I had exhausted a lot of the simple stuff, I targeted the other areas that I wasn’t hitting. I mean, how was my coded¬†test supposed to test my method that does an HTTP request and an FTP of a file under the hood?¬†Mocks.

So this is where you probably draw the line between your integration tests or unit tests and get all pedantic about it. But I don’t care how you want to separate it: I need coded tests that cover a section of my class so that I can ensure it behaves as I expect. But if I’m mocking my dependencies, how do I know my class is actually doing what I expect?

Instrument your mocks! This was totally cool for me to play around with for the first time. I had to create dummy FTP/HTTP requests that met the interface my class under test expected. Pretty easy. But I could actually assert what requests my class under test was actually trying to send out! This meant that if my method was supposed to try and hit a certain URL, I could assert that easily by instrumenting my mocked instance to check just that. Was it supposed to FTP a certain set of bytes? No problem. Use my mocked instance to assert those bytes are actually the ones my class under test is trying to send.

Wrap Up

This was just a general post, and I didn’t put up any code to go along with it. Sorry. I really just wanted to cover my experience with refactoring, interfaces, mocking, and code coverage because it was a great learning for me.

To recap on what I said in this post:

  • Identify the parts you want to mock. These are the things your class or method probably isn’t responsible for creating directly. Going out to the network? Accessing the disk? Accessing the environment your test is running under? Creating complex concrete classes because they hook into some other system for you? Great candidates for this.
  • Create interfaces by looking at the API you’re accessing. You know what classes you want to mock, so look how you’re using the API. If you need to access a few properties and methods, then make that part of your interface. If you see commonality between¬†a few similar things, you might be able to create a single interface to handle all of the scenarios.
  • Inject factories that can create¬†instances for you. These factories know how to create the concrete classes that meet your interfaces. In a real situation, they can create the classes you expect. In a test environment, they can create your mocks.
  • Write coded tests with your mocks! The last part is the most fun. You can finally inject some mocked classes into your classes/methods under test and then instrument them to ensure your code under test is accessing them in the way you expect. Run some code coverage tools after to prove you’re doing a good job.

I hope my experiences down this path are able to help you out!


Leadership: What Does It Mean? – Weekly Article Dump

Leadership: What Does It Mean? - Weekly Article Dump

Leadership

Everyone has their own variation of what leadership means. For me, leadership means empowering others to accomplish their goals and providing assistance when they need it. There were a few articles that came up on LinkedIn this week that I wanted to share with everyone and discuss how they fit into my perspective on leadership.

Articles

  • Does Your Team Work With You Or For You?:¬†Kwame Manu-Antwi opens up the article in an interesting fashion. When I read the title of the article, I figured this was going to be the typical leadership vs management debate. However, Kwame goes into describing a scenario where he had a humbling experience from one of his team that made some sacrifices for him. This was truly an example of working for him.

    The entire second half of the article shares a bunch of leadership traits that I think are really beneficial. ¬†For example, being transparent and encouraging growth in your team members. I think the point that is being made in this article, although I don’t personally feel like it was made as obvious as it could have been, is that as a leader, if you want to feel like your team is willing to make sacrifices (for you, or for the team) then practicing being an excellent leader is the way to get there. Thus, the tips he provides to do so!I’d say there’s a lot of takeaway in his bulleted leadership points.

    If you’re an experienced leader then it’s probably mostly stuff you’ve heard before. However, it never hurts to be reminded of great leadership responsibilities!

  • How Do I Hire A Good Employee: Insights on Leadership Traits: In this article¬†Kendall Matthews talks about the specific things he looks for when interviewing. It’s not about how picking the smartest person in the world or the most skilled person according to Kendall. It’s all about finding people that have that curious drive that can think on their feet. Have you given into the status quo?

    When it comes to leadership and hiring, your responsible for building out a well rounded team. In my opinion sometimes this will require hiring the smartest or most skilled person, but more often than not, you’re just looking for go getters. People that are curious by nature and always looking to push the boundaries make great candidates for your team because they’re adaptable. This means you don’t need to go finding someone with the perfect skill set because you can hire the person that’s willing to evolve into that person.

    Again, it’s not a blanket rule in my perspective. Sometimes your team will require that super-skilled person to be up and running from day one. Being a good leader in charge of hiring requires you to understand your teams needs though.

  • Can Skipping a Meeting Make You a Better Leader?: I find that Ilya Pozin always has some interesting articles up on LinkedIn. If you don’t follow him yet, I suggest you do! This article is all about shaking things up to align them to your leadership strategy (and not just accepting meeting invites and then not showing up).The first part of the article is really about taking charge of your daily routine. If you get into work and your ready to make a big dent in your todo list, then moving meetings until later in the day might have a huge ¬†benefit. Similarly, it helps you plan out and prioritize the rest of your day. For me, I plan the night before and since I’m still largely a developer, I find that if I have meetings in the middle of the day when I’m in my groove then that’s when I have the biggest problems. Try tweaking when your meetings are to suit your leadership style.

    The second part of this article talks about the idea of a devil’s advocate and is personally my favourite part. I can’t stress enough how important healthy debate is for continuously improving. I had a colleague the other day say that he doesn’t like how often he hears “because it’s always been that way”. I jokingly responded, “because we’ve always said that”! But the point is, he’s not sticking to the status quo and doesn’t want to settle. I had another colleague argue against my perspective even more recently, and it really got me thinking about how our perspectives were different and where we might need to go next. Healthy debate is awesome. Your goal is not to put your “opponent’s” face in the dirt, but to understand their perspective as much as possible and ensure they get your perspective as much as possible.

  • Heisenberg Developers: In his article, Mike Hadlow talks about how a new (what seems to be scrum-based approach?) was introduced to a software development team and how it negatively impacted them. Mike’s argument? The process that was put in place took away autonomy from developers–they should be given free reign to implement a feature as they see fit.

    While the general consensus in the comments on his blog indicates that people agree, I actually don’t. I’m well aligned to the first two sentences in his closing paragraph (autonomy and fine grained management) being important, but I think direction is incredibly important. In an agile shop, often the customer proposes features to go into the product (and when the customer isn’t available, product owners acting on behalf of the customer propose the features) and the developers work to get them done. Maybe this wasn’t the implication of the blog post, but I don’t think it makes sense to just let developers randomly choose which of the features to work on next and decide on their own how to do it.

    What works better, in my opinion? Have product owners provide acceptance criteria for what would make the feature successful. Have software testers and software developers mull over the acceptance criteria and bounce ideas back off of the product owners. Did they think of how that would affect feature B? Do they realize it will be a support or regression testing nightmare unless feature C is in place? What’s my point? Collaboration. The article doesn’t even mention it. It’s only about how process takes away from the artistic nature of programming. I feel like people should stick to hobby programming if it’s art they want to express, but when it comes time to business, it’s about delivering rock solid features that the customer wants.

    Back to estimating and tasking out features. Why break a feature down? What’s good about doing it that way? If you hit road blocks or need to pivot, it’s great to have a part of a feature done and realize that in it’s current state it might be classified as acceptable for a deliverable. Maybe it doesn’t match the original acceptance criteria, but perhaps the pivot involves adjusting that and now it’s acceptable. Task breakdown brings insight to the people working on the feature. What’s involved in making it? How are you going to test it? How are you going to support it?

    Autonomy is important. But I think that there needs to be some level of process in place for leadership in management to have insight as to what’s taking place, and there needs to be enough autonomy for developers and testers to do their job to the best of their ability. Sometimes the time invested in collaborating is one of the best investments in your development team.

  • Why The Golden Rule Sucks:¬†Joaquin Roca has an awesome article on “The Golden Rule” and why it doesn’t apply in leadership. Joaquin starts by discussing why building a diverse team is incredibly important and why you should take advantage of the tensions it can create. So why does The Golden Rule suck? Well… not everyone is like you and not everyone wants to be engaged the same way you are. Everyone is different and it’s important to adapt your ways to the person you are engaging with–especially when your team is diverse. There’s also a cool leadership quiz that he has posted at the top of the article!
  • Did I Make a Mistake in Promoting This Person?!: This article is about something that happens in the tech world all too often.¬†Caroline Samne¬†talks about how skilled professionals are promoted into leadership in management positions–except they don’t have any expertise in this area. I’m actually a prime example of this. I was hired on as a developer early on at Magnet Forensics, and before expanding the team, I was chosen for a leadership position without any past experience. However, like the article says, I had great mentorship through our HR manager and I was empowered to seek learning opportunities to grow in this space. The moral of the story is, just because someone is skilled at X, it doesn’t mean they’ll turn out to be a great (people) leader in this space. Leadership just doesn’t work magically like that.
  • Corporate Hackathons: Lessons Learnt:¬†Christophe Spoerry‘s article is all about hackathons. It’s a great way to spur some innovation in your organization if you’re allowing it to happen naturally. He shares his learnings from past experiences such as having leaders with past experience in hackathons present and having teams and/or themes picked out ahead of time. Once the hackathon starts, you don’t want to be wasting time with logistics… You want to be participating! Discuss what the outcome of the hackathon will be. Who’s going to take ownership over what was created? How will the outcomes be shared with the other participants or the rest of the organization? Get hackin’!

Thanks for reading! Follow Dev Leader on social media outlets to get these updates through the week.


IronPython: A Quick WinForms Introduction

IronPython: A Quick WinForms Introduction

Background

A few months ago I wrote up an article on using PyTools, Visual Studio, and Python all together. I received some much appreciated positive feedback for it, but really for me it was about exploring. I had dabbled with Python a few years back and hadn’t really touched it much since. I spend the bulk of my programming time in Visual Studio, so it was a great opportunity to try and bridge that gap.

I had an individual contact me via the Dev Leader Facebook group that had come across my original article. However, he wanted a little bit more out of it. Since I had my initial exploring out of the way, I figured it was probably worth trying to come up with a semi-useful example. I could get two birds with one stone here–Help out at least one person, and get another blog post written up!

The request was really around taking the output from a Python script and being able to display it in a WinForm application. I took it one step further and created an application that either lets you choose a Python script from your file system or let you type in a basic script directly on the form. There isn’t any fancy editor tools on the form, but someone could easily take this application and extend it into a little Python editor if they wanted to.

Leveraging IronPython

In my original PyTools article, I mention how to get IronPython installed into your Visual Studio project. In Visual Studio 2012 (and likely a very similar approach for other versions of Visual Studio), the following steps should get you setup with IronPython in your project:

  • Open an existing project or start a new one.
  • Make sure your project is set to be at least .NET 4.0
    • Right click on the project within your solution explorer and select “Properties”
    • Switch to the “Application” tab.
    • Under “Target framework”, select ¬†“.NET Framework 4.0”.
  • Right click on the project within your solution explorer and select “Manage NuGet Packages…”.
  • In the “Search Online” text field on the top right, search for “IronPython”.
  • Select “IronPython” from within the search results and press the “Install” button.
  • Follow the instructions, and you should be good to go!

Now that we have IronPython in a project, we’ll need to actually look at some code that gets us up and running with executing Python code from within C#. If you followed my original post, you’ll know that it’s pretty simple:


var py = Python.CreateEngine();
py.Execute("your python code here");

And there you have it. If it seems easy, that’s because it is. But what about the part about getting the output from Python? What if I wanted to print something to the console in Python and see what it spits out? After all, that’s the goal I was setting out to accomplish with this article. If you try the following code, you’ll notice you see a whole lot of nothing:


var py = Python.CreateEngine();
py.Execute("print('I wish I could see this in the console...')");

What gives? How are we supposed to see the output from IronPython? Well, it all has to do with setting the output Stream of the IronPython engine. It has a nice little method for letting you specify what stream to output to:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(yourStreamInstanceHere);

In this example, I wanted to output the stream directly into my own TextBox. To accomplish this, I wrote up my own little stream¬†wrapper that takes in a TextBox and appends the stream contents directly to the Text property of the TextBox. Here’s what my stream implementation looks like:


private class ScriptOutputStream : Stream
{
  #region Fields
  private readonly TextBox _control;
  #endregion

  #region Constructors
  public ScriptOutputStream(TextBox control)
  {
    _control = control;
  }
  #endregion

  #region Properties
  public override bool CanRead
  {
    get { return false; }
  }

  public override bool CanSeek
  {
    get { return false; }
  }

  public override bool CanWrite
  {
    get { return true; }
  }

  public override long Length
  {
    get { throw new NotImplementedException(); }
  }

  public override long Position
  {
    get { throw new NotImplementedException(); }
    set { throw new NotImplementedException(); }
  }
  #endregion

  #region Exposed Members
  public override void Flush()
  {
  }

  public override int Read(byte[] buffer, int offset, int count)
  {
    throw new NotImplementedException();
  }

  public override long Seek(long offset, SeekOrigin origin)
  {
    throw new NotImplementedException();
  }

  public override void SetLength(long value)
  {
    throw new NotImplementedException();
  }

  public override void Write(byte[] buffer, int offset, int count)
  {
    _control.Text += Encoding.GetEncoding(1252).GetString(buffer, offset, count);
  }
  #endregion
}

Now while this isn’t pretty, it serves one purpose: Use the stream API to allow binary data to be appended to a TextBox. The magic is happening inside of the Write() method where I take the binary data that IronPython will be providing to us, convert it to a string via code page 1252 encoding, and then append that directly to the control’s Text property. In order to use this, we just need to set it up on our IronPython engine:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(new ScriptOutputStream(txtYourTextBoxInstance), Encoding.GetEncoding(1252));

Now, any time you output to the console in IronPython you’ll get your console output directly in your TextBox! The ScriptOutputStream implementation and calling SetOutput() are really the key points in getting output from IronPython.

The Application at a Glance

I wanted to take this example a little bit further than the initial request. I didn’t just want to show that I could take the IronPython output and put it in a form control, I wanted to demonstrate being able to pick the Python code to run too!

Firstly, you’re able to browse for Python scripts using the default radio button. Just type in the path to your script or use the browse button:

IronPython - Run script from file

Enter a path or browse for your script. Press “Run Script” to see the output of your script in the bottom TextBox.

Next, press “Run Script”, and you’re off! This simply uses a StreamReader to get the contents of the file and then once in the contents are stored in a string, they are passed into the IronPython engine’s Execute() method. As you might have guessed, my “helloworld.py” script just contains a single line that prints out “Hello, World!”. Nothing too fancy in there!

Let’s try running a script that we type into the input TextBox instead. There’s some basic error handling so if your script doesn’t execute, I’ll print out the exception and the stack trace to go along with it. In this case, I tried executing a Python script that was just “asd”. Clearly, this is invalid and shouldn’t run:

python_error_asd

Python interpreted the input we provided but, as expected, could not find a definition for “asd”.

That should be along the lines of what we expected–The script isn’t valid, and IronPython tells us why. What other errors can we see? Well, the IronPython engine will also let you know if you have bad syntax:

python_error_bad_syntax

Python interpreted the script, but found a syntax error in our silly input.

Finally, if we want to see some working Python we can do some console printing. Let’s try a little HelloWorld-esque script:

python_pass_hello_world

Python interpreted our simple Hello World script.

Summary

This sample was pretty short but that just demonstrates how easy it is! Passing in a script from C# into the IronPython is straight forward, but getting the output from IronPython is a bit trickier. If you’re not familiar with the different parts of the IronPython engine, it can be difficult to find the things you need to get this working. With a simple custom stream implementation we’re able to get the output from IronPython easily. All we had to do was create our own stream implementation and pass it into the SetOutput() method that’s available via the IronPython engine class. Now we can easily hook the output of our Python scripts!

As always, all of the source for you to try this out is available online:

Some next steps might include:

  • Creating your own Python IDE. Figure out some nice text-editing features and you can run Python scripts right from your application.
  • Creating a test script dashboard. Do you write test scripts for other applications in Python? Why not have a dashboard that can report on the results of these scripts?
  • Add in some game scripting! Sure, you could have done this with IronPython alone, but maybe now you can skip the WinForms part of this and just make your own stream wrapper for getting script output. Cook up some simple scripts in a scripting engine and voila! You can easily pass information into Python and get the results back out.

Let me know in the comments if you come up with some other cool ideas for how you can leverage this!


Be a Better Programmer – Weekly Article Dump

Be a Better Programmer - Weekly Article Dump (Image by http://www.sxc.hu/)

Be a Better Programmer

It’s a new year and that means it’s all about resolutions, right? Well, I’m not a huge fan of keeping around a resolution that needs to wait for a new year, but I am a fan of reflecting on your goals and your skills. If you’re a programmer like me, then maybe this will be a great starting point. In my weekly article dumps I usually would just provide a couple of comments on a link like this, but I felt I should dive in a little bit more. You can find the original article by Amy Jollymore over here. Please have a look! I shared it with the whole dev team at Magnet Forensics because I felt there was a little bit of something for everyone.

Number one on this list, and perhaps the one I’d personally like to focus on more out of this list, is checking your code before blaming others. Blaming other people–in general, not just programming–is an easy way out. When a problem occurs, it’s simple to assume that all of your work is right and that it must be someone else’s fault. But if everyone starts thinking like this, it turns into a nasty blame war. So next time the build breaks or your shiny new feature stops working as expected, don’t go blaming other people. Investigate what the problem is. See what your most recent changes were and if they could have caused the problem. As you start to gain confidence that your changes aren’t responsible for the issue, try sitting down with one or two other people you think might have been around the problem area recently–But don’t go accusing them! Putting your heads together to figure out the problem can speed up the process and might even shed some light on some miscommunication over a design or some assumptions in the code that don’t actually hold true. It’s a lot more embarrassing to blame someone when it’s actually your fault compared to putting in the effort and admitting you might have goofed up. Try it out!

Number two is also a great item. You should never put an end to your learning… especially as an individual in a technology space. There are so many great suggestions listed for this point that there’s no point in me repeating them. Just go read them! An interesting point worth mentioning is using podcasts for learning. This is a great option if you find you’re brain is still spinning when you lay down in bed or if you have a long commute to work (or something else you’re involved in). The author also mentions that you don’t need to be learning programming… What about domain expertise? If you’re writing code for banks, lawyers, or digital forensics… Why ¬†not learn about that too?!

The last point I’ll touch on from the article is number three: don’t be afraid to break things. I love this point. If you’re working on a big piece of software, there are almost certainly areas that seem brittle, scary, or just plain incomprehensible. If your project is still small, it very well get to this point. It doesn’t mean that the code is bad or that you’re working with the worst programmers… It’s just something that happens when you’re continuously trying to build on your software. The real problem occurs when nobody is willing to take the time to go change things. If you have big scary brittle parts of code, then set aside some time, take a deep breath, and go refactor it! It might seem like hell at first, but once you get into it (and especially after it’s done) you’ll feel a million times better. Plus, now your code can continue to be built upon without people running in fear when you mention that section of code. Code can get nasty, but consider using a “tech debt” system or regularly set aside time for refactoring parts of your code base.

Again, the original article is located at: 7 Ways to be a Better Programmer in 2014. Check it out!

Articles

  • How to Manage Dynamic Tensions ‚ÄĒ and Master the Balancing Act: This was an interesting article on some parts of leadership that often oppose each other. Author¬†Chris Cancialosi does an excellent job in discussing balance between internal and external influences as well as leading and managing. A good take away from this article is at least acknowledging that there are certainly some things to balance. You may want to have the most flexible team, but have you considered if there’s a “too flexible”? Just a bit of perspective that this article might bring to light.
  • A Crash Course In Leadership For 20-Something CEOs: Barry Salzberg‘s article is geared toward young CEOs, but I think that means we can apply the lessons to anyone looking to lead! A few of the points I’d like to mention include being tough on problems and not on people. Your people are the one’s who are going to solve problems and bring great ideas to the table. They’ll invest their time into your organization in order to accomplish great things–so don’t be hard on them. Instead, acknowledge that your problems and challenges are the things you want to crush, and work with your team to make sure you conquer every challenge that gets in the way of your goal. Another point is on taking risks. Never taking risks is a great way to stagnate. You need to learn from your failures, but keep pushing the boundaries. Finally, be ready to adapt. As your organization grows or as the market you’re working within evolves, you need to be ready to adapt and change. You might get lucky and things don’t change all that much over a long period of time, but the odds of that are pretty low. Be ready to adapt so when the time comes, you don’t need to worry about everything falling apart.
  • Leading at Scale with Agility: Brad Smith has a few great points on what leading a team should encompass. First, a team should have a goal that it is trying to achieve. If that team is part of a larger organization, the team’s goal should align with the goal of the entire organization. Secondly, decisions for the team should involve those on the team. It’s easy to sit back and speculate what might be best, but why not involve the people directly affected? Of course, this is more difficult for large teams but maybe that’s an indication your teams would be more effective if they were smaller. Next, empower teams to arrive at solutions on their own. If a plan worked out well, try communicating it to others to try out. Conversely, if the plan had some problems, let others on the team (or other teams) know about the hurdles. Finally, Brad has a point on trust. Trust is arguably one of the most important parts of leading a team. Each team member needs to be able to trust the others. There should be an easy assumption that everyone is operating with best intentions.
  • For Leaders, Today is History: In this article by Steven Thompson, he gives a high-level overview of his focus. Specifically, he focuses on the future and not right now. Steven says the teams he is in charge of are often looking at the problems of “right now” and perhaps a little bit in the future. It would be counter productive for him to try and butt-in to try helping with those problems because he’s so far removed from them. Instead, those individuals have been empowered to focus on those problems. Instead, Steven focuses on the future–the direction of the teams. As a leader, it’s important to try and be thinking at least one step ahead.
  • What If You Had to Write a “User Manual” About Your Leadership Style?: After I read Adam Bryant‘s article, I thought the idea of a leadership “user manual” would be pretty cool. Even if there isn’t a single other individual who would benefit from it, at least it would help reveal to myself some of my leadership quirks. That’s useful on it’s own! I’ll be sure to post up my leadership “user manual” when I have it complete… and I imagine I’ll have to keep updating it over time as my style evolves. It’ll be really interesting to see the evolution of my leadership style! Why not consider doing one for yourself?
  • What Bosses Should Never Ask Employees to Do: Jeff Haden‘s article was a little bit controversial in my opinion–and in the opinion of some of the commenters. I think I get the underlying message behind a lot of what Jeff is saying for each of his points, but as one commenter said, it sounds like a bit of a personal complaint the whole way through. Consider the topic of donating to charities at work. The feel I get after reading that segment is that your organization should not attempt to do fundraising through employees. While I don’t actually think that’s what Jeff is saying, that’s how I feel after reading it. I know that we’ve been able to do several charity events at Magnet, and we’ve always said that they are completely voluntary. I think that’s the crucial part. It’s the holiday season and your budget is a bit tight? How could anyone get mad at you for backing out of a completely optional charity donation? Busy with some personal matters or want to focus on finishing up something at work the day we’re doing a charity event? No big deal, it’s optional. Anyway, the point is that perhaps based on the wording in the article, I felt like some of the messaging will be misinterpreted. I think there are some good points buried in there. Check it out and let me know if you agree or not!

Follow Dev Leader on social media outlets to get these updates through the week. Thanks!


Movember Wrap-up – Weekly Article Dump

Movember Wrap-up - Weekly Article Dump

Movember Wrap-up

At the start of December, it’s time for a lot of us to shave off our glorious Movember badges from our upper lips. This year, MoMagnets did an absolutely amazing job raising money for Movember. At the time of writing, we’re sitting at just under $2400! An incredible effort by Magnet Forensics and all of those that helped with their generous contributions.

My ‘stache didn’t quite get to where I wanted to this year. It was close, but it was another connector-less Movember for me. I was almost able to get some twisting done for some not-so-legitimate connectors. Oh well… Here’s what I ended up rocking for most of the month:

Movember Wrap-up - Nick's Final 'Stache

My final Movember creation: The Anti-Connector.

Matt Chang definitely took the lead for raising the most of all the MoMagnets members at over $700! Mica Sadler is sitting in second at just under $400. That’s nearly half the team’s total between these two beauties. We also had a very gracious contribution from our CEO that I wanted to call out. Thanks so much, Adam!

There’s still a bit of time left before donations are closed for the 2013 Movember season. We have until the 9th to get some final contributions in! If you’re feeling generous, please visit our team page and make a contribution. Every little bit helps, and we greatly appreciate it!

Articles

  • Top 5 Reasons People Love Their Jobs and How You Can Love Yours, Too: Some great points on why people love their jobs. Some of these may be pretty obvious, but it’s important to be reminded about what keeps people engaged. Among the top things: the work culture, the amazing people you get to work with, and autonomy. If you’re trying to create an awesome place to work (or if you’re looking for an awesome place to work) then these are probably things you’ll want to focus on!
  • 5 Things Zapping Your Company’s Productivity: Ilya Pozin always has some interesting articles. This article takes the perspective that some of the fancy perks or awesome processes you have in place may actually be hindering productivity. One common theme that was brought up under two separate points in this article is that sometimes people need a spot where they can work in peace. People like having an fun collaborative culture, but many personality types require some quiet time in order to buckle down.
  • Reduce Your Stress in 2 Minutes a Day: I’m not the type of person that truly believes doing one tiny thing for only a moment every day is going to have an enormous positive impact on your life. However, I do think that if you can take the time to try and do a few little things here and there, that overtime, you’re likely to have more a positive outlook. In this article,¬†Greg McKeown¬†shares a few tips on relaxing and trying to regain some focus. I don’t think it’s anything that’s going to be life-changing, but it never hurts to think about different ways to catch your breath.
  • Building a fast-failure-friendly firm: This was a pretty cool series of slides put together by Eric Tachibana that I thought was worth sharing. There are lot’s of articles on failing and why it’s important–especially for innovating. This series of slides provides a high level perspective on how you can approach failing… the right way!
  • Code Smells ‚Äď Issue Number 3: This is an article I wrote about Code Smells. This entry talks about the use of exception handlers to guide logical flow in your code and alternatives for when your class hierarchy starts to get too many very light weight classes. As always, I’d love to get your feedback. If you have other code smells, or a different perspective on the ones that I’ve posted, please share them in the comments!
  • 5 Bad Thoughts That Will Throw You Off Track: This short little list is worth a quick read through. There are a ton of things that distract us every day, but the distractions you can easily control are the ones that you cause. Examples? Don’t take on too much at once. Don’t try to make every little thing you do perfect. It’s a quick read, but well worth the reminder!
  • Not Crying Over Old Code: Another programming article for this week. As the article says, the common meme for programming is that your old code is always bad code. However, there should be a point in your programming career where old code isn’t bad, it’s just different than how you might have approached it now. If your always experiencing your old code being bad, then maybe you’re not actually that great at programming yet! Or… maybe you’re just too damn picky.
  • Things I Wish Someone Had Told Me When I Was Learning How to Code: This article by Cecily Carver is something I’ve been hoping to come across for a while now. It’s another programming article–a good read for experienced programmers but incredibly important for newbies to check out. Cecily covers some of the roadblocks you experience early on, like code never (almost never) working the first time, or things you experience throughout your programming career, like always being told of a “better” alternative. I highly recommend you read through this if you dabble in programming, or if you’ve ever considered it.

Please¬†visit our team page¬†for MoMagnets and make a Movember contribution if you’re able to!¬†Remember to follow¬†Dev Leader¬†on social media outlets to get these updates through the week. Thanks!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+
Nick’s CodeProject Articles


Code Smells ‚Äď Issue Number 3

Code Smells ‚Äď Issue Number 3 (Image by http://www.sxc.hu/)

Code Smells

Welcome to the third edition of Code Smells! Periodically I’ll be posting about how to detect code smells and what they mean in terms of the big picture of your code. The previous installment can be found right here.

What’s a code smell? Wikipedia says it perfectly:

In¬†computer programming,¬†code smell¬†is any¬†symptom¬†in the¬†source code¬†of a¬†program¬†that possibly indicates a deeper problem. Code smells are usually not¬†bugs‚ÄĒthey are not technically incorrect and don‚Äôt currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.

These code smells are often based on my own opinion and experience with programming. If you disagree with what I’m saying in my post, please don’t hesitate to post a comment. I’d love to clarify anything I may have worded poorly and discuss your perspective–especially if you have a completely different take on things!

The Stink List

Code Smell #7: Using exceptions to control logical flow. This is a pretty nasty path to get into and a bad code smell to stumble upon. Luckily, it’s generally relatively easy to improve. Using exception handling to control logical flow is, in general, misleading. It’s relying on a mechanism used to catch unexpected errors in order to direct the flow of your program. Often times we can use things like if statements to check for these conditions before throwing exceptions.

A common scenario where I see this is parsing. I’ll illustrate this code smell with a little C# example:


var input = "This is not a number";
try
{
  var parsed = int.Parse(input);
  DoSuccessfulStuff(parsed);
}
catch (Exception)
{
  DoFailStuff();
}

It seems a bit contrived, but I’ve seen lots of code written like this–and you know what? This works. It gets the job done. However, there are other mechanisms built-in to .NET that let us do parsing a little bit nicer:


var input = "This is not a number";
int parsed;

if (int.TryParse(input, out parsed))
{
  DoSuccessfulStuff(parsed);
}
else
{
  DoFailStuff();
}

The second set of code doesn’t need to catch exceptions to know that the parsing wasn’t successful. It may not be obvious from this example but throwing and catching exceptions can be quite expensive¬†compared to a few logical sanity checks instead (and before getting into a debate on this, just know the impact it has on your program. I’ve had things go from taking several seconds to multiple minutes, but there are certainly cases where performance will be negligible).

The additional kicker in my contrived example is using the base Exception class to create what a colleague of mine refers to as¬†Pokemon Exception Handlers. Thus, even if you didn’t want to restructure your code, using a specific exception type would:

  • Indicate to other programmers what you’re trying to accomplish
  • Not swallow other potential problems and have them go unseen

Now, this code smell isn’t always possible to avoid entirely. If you’re interfacing with third party components, sometimes you do have to rely on catching exceptions that you can’t otherwise check for ahead of time. If you don’t have the code, you can’t know for every path how/when/why exceptions will be thrown. The same thing could be said when running within an environment where state cannot be guaranteed. Sometimes it’s just necessary. In this case, I would suggest that instead of using Pokemon Exception Handlers, you try to catch the specific exceptions you know you need to watch out for.

Takeaway:

  • If a simple logic check can be used instead of throwing/catching exceptions, it’s likely a better bet.
  • Try to avoid exception handlers that catch all exceptions. Something nasty might sneak by as a result of it.
  • Interfacing with some code or working working in certain environments means you have to rely on exception logic. Take a deep breath and move on.

Code Smell #8: Having an object hierarchy that requires many very light weight classes. Object oriented programming and how object hierarchies are structured are pretty complicated topics of discussion, so I’m not about to try and over simplify it with discussion of this code smell. This is mostly something I’ve gathered from my own programming experience, so I’ll try to illustrate with examples that parallel things I would have come across.

When I’m building an object hierarchy, sometimes it’s not really apparent just how big and complicated it might get. I might start off with a base class and two child classes of it. Over time, the top three levels in my hierarchy have all turned into some sort of class abstraction, and I don’t hit concrete implementations until a few levels down hte hierarchy. Not a big deal–Sometimes it’s just hard to tell where things will go. When things get to the point where in order to introduce a new class and functionality all I need to do is inherit a class and override a single property or method, that’s a bit of a red flag for me.

On the surface, this seems pretty cool. The hierarchy is apparently solidified enough that extending it is really simple if all I need is a single property or method replacement. So why is this a code smell?

In my opinion, it has to do with the duplication of code. If I end up having many child classes (where child in this case represents the child-most class of my mature object hierarchy) that differ only by a single property or method, then I should look at how these classes are being constructed. I wrote recently about how I used lambda expressions to refactor similar code with classes that differed by a single method. My solution, in this case, was to examine the factory that created my classes. Instead of having 10’s of different child classes with a bunch of boilerplate code, I had one factory that could specify the code that differentiated each class.

The benefit of this?

  • Keep class hierarchies from ballooning our of control. Changing an API down the road can mean making changes in many spots.
  • Reduce duplication of boilerplate code. This might be the code required to define a simple constructor or override a getter property.

This is only one small example, but if you get into this situation in your class hierarchy, I’d recommend investigating to see if you can refactor in a similar approach. Maybe your class hierarchy is incredibly mature and isn’t changing much. If that’s the case, you may not even want to touch it. So be it. If you’re still actively adding classes to your hierarchy, it may be better to try analyzing it sooner rather than later.

Takeaway:

  • Object oriented design is a complex topic of discussion.
  • There’s no one perfect way to make your class hierarchies.
  • Having many child classes that differ by a property/method or two may be worth checking for refactoring opportunities.

Summary

I hope you enjoyed this issue of Code Smells. As always, it’d be great to open the floor to discussion. I don’t believe in absolutes, so identifying code smells is not meant to be me preaching some made up laws of programming. Let me know your thoughts on these code smells or share code smells of your own!


Performance Reviews – Weekly Article Dump

Performance Reviews - Weekly Article Dump (Image by http://www.sxc.hu/)

Performance Reviews

It’s almost the end of the year, and performance reviews for many companies are just around the corner. This will be the first time for me sitting on the other side of a performance review. I’m excited, and to be honest, a little nervous about how it will all play out. I know our HR manager has done an excellent job putting together our initial take on performance reviews, but it’s still going to be up to me to ensure that all aspects of a performance review are communicated properly to my team. It’s definitely going to be an interesting time of year!

I’ve started doing a little bit of reading on performance reviews. From what I can tell, the general consensus is that most performance review systems are flawed and nobody knows the perfect way to do them. That’s kind of scary actually. So, like anything, I started questioning all the aspects of performance reviews that I can think of. So things like: What’s stack ranking? Why do companies stack rank? What are alternatives? What about leveraging teammate-driven reviews? etc… There’s a whole lot for me to learn, so I need to start by questioning everything.

With that said, how do you do performance reviews? Have performance reviews been working at your organization? Do you stick to “the norm”, or do you have your own interesting spin on performance reviews that make them effective for your organization?

Articles

  • Employee retention is not just about pizza lunches and parties: On the surface, things like candy stashes, catered lunch, and all other shiny perks seem like a great way to get and keep employees. However, keeping employees engaged is the sum of what attracts them to the company and what keeps them motivated while they’re working. Recognizing their accomplishments and giving them challenging and meaningful work is an awesome start.
  • 7 Reasons Your Coworkers Hate You: The truth? You probably know at least one person at work who does at least one of the things on this list. The harder truth? You probably do one of these yourself. It’s a pretty cool list put together by Ilya Pozin. I’d suggest a quick look!
  • How To Inspire Your Team on a Daily Basis: In this article by¬†James Caan, he echoes one of the things I wrote about recently. You can’t expect to have a motivated team unless you lead by example. You really shouldn’t expect anything from your tea unless you are going the lengths to demonstrate that your dedication to the team and the team’s goal.
  • humility = high performance and effective leadership: Michelle Smith¬†write about how humility is actually a great leadership characteristic. A couple of the top points in her article include not trying to obtain your own publicity and acknowledge the things you don’t know. The most important, in my opinion, is promoting a spirit of service. You lead because you are trying to provide the team guidance and ensure every team member can work effectively.
  • The Surprising Reason To Set Extremely Short Deadlines: This one might not be the same for all people. I think that anyone that tries to apply this as a blanket statement is probably setting themselves up for failure. How do you feel about short deadlines? Some people tend to work really well under pressure and having short deadlines. For those that do, this article offers a perspective on why. Under pressure, you operate creatively given your restricted set of resources, and you don’t have time to dawdle and let things veer of track. Interesting to read.
  • Eliciting the Truth: Team Culture Surveys: Gary Swart¬†talks about something I think is extremely important for all businesses. Maybe your work culture is established, but where did it come from? It’s easy for people to get together in a room and say “we want to have a culture that looks like X”. It’s harder to actually have the culture you say you want. Gary suggests you do a culture survey to actually see what your work culture is like because… well, who knows better? A few people sitting together in a room, or everyone in the company?
  • You Are Not a Number: With year-end performance reviews and the like coming up, I thought it would be interesting to share this short article by¬†Dara Khosrowshahi. Do you stick to stack ranking? Do you have in-depth conversations with employees about their performance? Have you tried switching things up because the canned approach just wasn’t delivering?
  • Which Leads to More Success, Reward or Encouragement?: Deepak Chopra¬†analyzes the positives and negatives of using rewards and using encouragement as a means of driving success. The takeaway from Deepak’s article is that using rewards is not a sustainable means to motivate your team, and actually tends to create separation within the team. By leveraging encouragement, you can empower your team to work together and self-motivate.

Remember to follow Dev Leader on social media outlets to get these updates through the week.

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+
Nick’s CodeProject Articles


Deloitte Companies to Watch – Weekly Article Dump

Deloitte Companies to Watch - Weekly Article Dump

Deloitte Companies to Watch

Another impressive accolade for Magnet Forensics! Deloitte has placed Magnet on their top 10 companies to watch list! To qualify for the list, the companies need to be operating for less than five years, be based out of Canada, and put a large portion of their revenue to generating intellectual property. Our CEO, Adam Belsher, had this to say about the award:

‚ÄúWe are honoured to be named one of Deloitte‚Äôs Companies-to-Watch. This award recognizes the hard work and dedication of our team. We‚Äôre thankful for the success we‚Äôve achieved, and we‚Äôre incredibly proud to be contributing to the important work done by our customers who use our solutions to fight crime, enhance public safety, protect companies from fraud and theft, and ensure workplace safety and respect for their employees.‚ÄĚ

Magnet Forensics Press & Events

The event was put together very well. It was great to be able to interact with individuals from the other companies and share success stories. I even had a chance to meet up with Stephen Lake of Thalmic Labs¬†and have a good chat with him.¬†I’m going to name-drop him everywhere I go because he’s my old university room/house mate! He also happens to be a incredible person that if you have the chance to meet, you absolutely should. Here’s some coverage on twitter¬†of us talking with our founder Jad Saliba:

We enjoyed the whole night, and we were grateful for Deloitte putting on the event. The entire Magnet team is very proud of our achievements.

Articles

  • What comes first: employee engagement or great work?: A short but interesting article on employee engagement. The author claims that most employees probably start of at their position very motivated and engaged. Over time, an employees engagement drops if their leaders are not proactive in keeping their engagement levels up. By proactively acknowledging the success of your employees, you can keep your team engaged and producing great work.
  • Great Leadership Starts and Ends with This: Jeff Haden¬†put together this quick little article about an answer an audience member gave about what the key to leading people is. Caring. Overly simplified? Well, the individual went on to say that regardless of all of your strategies, plans, and experience, if you can’t prove that you truly care about your team then they aren’t going to buy in. I’m never one to buy into something so absolute, but the takeaway for me is that team members cannot be looked at entirely as resources. Sure, the people on your team affect productivity and in that sense are resources, but forgetting to acknowledge the human side of things is a recipe for failure.
  • 9 Ways to Win Employee Trust: In his article,¬†Geoffrey James¬†put together a great list of nine things to help build trust with your team. I wouldn’t say these are groundbreaking things, but it’s important to be reminded about them. Try reflecting on his list and seeing if you actually do the things you think you do. You might be surprised. Some of the top things on the list for me are ensuring employees’ success is number one on your priorities, listen more than you talk, and walk the walk. Great list!
  • Lambdas: An Example in Refactoring Code: I put out this programming article earlier this week and had some great feedback. In this article, I talk about a real world example of how using lambda expressions in C# really helped when refactoring a piece of code. Some people have never heard of lambdas, and some people seem to hate them. In this case for me, it greatly simplified a set of code and reduced a bunch of extra classes. I definitely owe it to myself to start investigating them a little bit more.
  • Executive Coaching: Bringing Out Greater Leadership: This article is all about taking charge with your leadership.¬†Judith Sherven¬†talks about executive coaching for leaders, but the main points I see in here are around confidence. If you aren’t confident in your ability to lead, motivate, and inspire how can you expect anyone else to be? It ends up becoming a tough balance, because you need to listen and take feedback from your team, but when you make decisions you should do so with confidence.
  • Stop Worrying About Making the Right Decision: Ever heard of paralysis by analysis? This article does a great job of explaining why you shouldn’t let that creep in to your leadership approach. It’s important to make good decisions–there’s no doubt about that. But the reality is that no matter what decision you make, there are certain unknowns that can creep in and potentially have a huge effect on the choices you’ve made. So what’s more important: making the perfect decision, or being able to adapt effectively?
  • Appraising Performance Appraisal: Steven Sinofsky‘s article is a bit of a beast, but it’s a great starting point if you’re reconsidering performance appraisals. Even if you’re totally content with your performance review system, it might be worth reading to spark some ideas. Steven does a great job of pointing out some common pitfalls of typical performance appraisal systems and comments on some things you really need to try and understand before sticking to any one system. I’m not well enough versed in the performance review and/or human resources side of things, but this article certainly has enough to get you questioning the common approaches.
  • Tab Fragment Tutorial: Shameless plug for my Android application that I put out on the Google Play store. It’s the end result of the tutorial I wrote up over here. I think it’s going to blow past my legitimate application for converting units!
  • Does a Good Leader Have To Be Tough?: Deepak Chopra¬†has some seriously great articles. In this article, he analyzes the pros and cons of being a “tough” leader. In short, there are positive takeaways from being a tough leader, but there are a lot of negative aspects to it. Deepak suggests you consider a different approach from tough-soft leadership. By focusing on a hierarchy of needs to be a successful leader, toughness is only one aspect of leadership. A pretty solid read, like all of Deepak’s articles.

Remember to follow Dev Leader on social media outlets to get these updates through the week.

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+
Nick’s CodeProject Articles


Lambdas: An Example in Refactoring Code

Lambdas: An Example in Refactoring Code

Background: Lambdas and Why This Example is Important

Based on your experience in C# or other programming languages, you may or may not be familiar with what a lambda is. If the word “Lambda” is new and scary to you, don’t worry. Hopefully after reading this you’ll have a better idea of how you can use them. My definition of a lambda expression is a function that you can define in local scope to pass as an argument provided it meets the delegate signature. It’s probably pretty obvious to you that you can pass in object references and value types into all kinds of functions… But what about passing in a whole function as an argument? And what if you just want to declare a simple anonymous method right when you want to provide it to a function? Lambdas.

So now you at least have a basic idea of what a Lambda is. What’s this article all about? I wanted to discuss a real-world coding experience that helped demonstrate the value of lambdas to me. In my honest opinion, I think having real world programming topics to learn from is more beneficial than many of the “ideal” scenario examples/tutorials you end up reading on the Internet. We can argue and debate that certain things are better or worse in an ideal sense, but when you have a real practical example, it really helps to drive the point home.

So for me, I love working with events. I’m very comfortable with the concept of delegation in C#. I can have one object that may notify anyone that’s interested that something is happening, and the other objects that do care are able to handle the event. Thus, actions can get delegated to those objects that care to be notified. One of my weaknesses at this point in my development experience is leveraging the concept of delegation outside of the realm of events. Delegation is powerful, but it’s certainly not limited to hooking onto events with event handlers.

The particular example I want to illustrate is a parallel of a real coding scenario. I was refactoring some code that was leveraging close to zero OOP practices. I wanted to create a nice extensible framework and class hierarchy to replace it. Once I was done, a few colleagues of mine at Magnet Forensics picked up on a bit of a code smell. We all agreed the new framework and class hierarchy was better, but there seemed to be a lot of boiler plate code going on. We got into the discussion of how lambdas could reduce a lot of the light-weight classes I had introduced. After taking their thoughts and refactoring my changes just a little bit more, the benefits of the lambdas were obvious to me.

So obvious, I had to write about it to share with all of you! Feel free to skip ahead to the downloads section to get the code and follow along with it. There are plenty of options for downloading.

The Scenario

I mentioned that this was a real world scenario. I’ve contrived a parallel example that hopefully demonstrates some of the real world issues while illustrating how lambdas are useful. Let’s imagine we have some big chunk of logic that does data processing. In my real-world scenario, this may have existed as one monolithic function. I would have one big function that, based on all the parameters I provide, can figure out how to process the data I feed it.

Problems:

  • Hard to test (You need to test the whole function even if you’re really just wanting to target a small part of it)
  • Error prone (Any small change to one part can potentially break an entire other part of the function as it grows in complexity)
  • Not extensible (As soon as you need to deviate a little bit from the structure that’s existed, suddenly things get really complicated)

By switching to more of an OOP approach, I can start to address all of the above problems. So in this example, I’ll illustrate what my initial refactoring would have looked like by introducing classes. Afterward, I’ll show what my second refactor may have looked like after taking lambdas into account. In order to stay true to some of the real world problems you might encounter when performing a big refactor like this, I’ve opted to include some fictitious dependency. I refer to this at the “mandatory argument” or “important reference”. You’ll notice in the code that I don’t really use it to do any work, but it’s demonstrating having to pass down some other critical information to my classes that the original function may have had easy access to.

Pre-Refactor: No Lambdas Here!

Let’s start with our new OOP layout. I want to have a factory that can create data processor instances for me. So let’s define what those look like.

First, we have the interface for our data processors:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public interface IProcessor
  {
    bool TryProcess(object input);
  }
}

And then a simple interface for a factory that can create the data processor instances for us:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public interface IProcessorFactory
  {
    IProcessor Create(ProcessorType type, object mandatoryArgument, object value);
  }
}

As you may have noticed, the factory interface I’ve provided above takes a ProcessorType enumeration. You may or may not agree that using an enumeration as an argument for the factory is good practice, but I’m using it to make my example simple. Here’s what our enumeration will look like:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public enum ProcessorType
  {
    GreaterThan,
    LessThan,
    NumericEqual,
    StringEqual,
    StringNotEqual,
    /* we could add countless more types of processors here. realistically,
     * an enum may not be the best option to accomplish this, but for
     * demonstration purposes it'll make things much easier.
     */
  }
}

And now we have a definition for all of the basic building blocks defined. These will also be used later when we refactor, so I wanted to get them out of the way right in the beginning.

Right. So, let’s create an extensible IProcessor implementation. We can address some of our basic requirements (like our artificial dependency) and create something that can easily be built on top of. All of our child classes will just have to handle validating their constructor input and overriding a single method. Easy!

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PreRefactor
{
  public abstract class Processor : IProcessor
  {
    private readonly object _importantReference;

    public Processor(object mandatoryArgument)
    {
      if (mandatoryArgument == null)
      {
        throw new ArgumentNullException("mandatoryArgument");
      }

      _importantReference = mandatoryArgument;
    }

    public bool TryProcess(object input)
    {
      if (input == null)
      {
        return false;
      }

      return Process(_importantReference, input);
    }

    protected abstract bool Process(object importantReference, object input);
  }
}

And now let’s provide the factory that’s going to be making all of these instances for us. Please not that the factory is left incomplete on purpose. I’ll only be providing two actual processor implementations and I’ll leave it up to you to try and fill out the rest!

using System;
using System.Collections.Generic;
using System.Text;

using LambdaRefactor.Processing.PreRefactor.Numeric;
using LambdaRefactor.Processing.PreRefactor.String;

namespace LambdaRefactor.Processing.PreRefactor
{
  public class ProcessorFactory : IProcessorFactory
  {
    public IProcessor Create(ProcessorType type, object mandatoryArgument, object value)
    {
      switch (type)
      {
        case ProcessorType.GreaterThan:
          return new GreaterProcessor(mandatoryArgument, value);
        case ProcessorType.StringEqual:
          return new StringEqualsProcessor(mandatoryArgument, value);
        /*
         * we still have to go implement all the other classes!
         */
        default:
          throw new NotImplementedException("The processor type '" + type + "' has not been implemented in this factory.");
      }
    }
  }
}

And now that we have a factory that can easily create our processors for us, let’s actually define some of our processor implementations.

We’ll start off with a simple processor for checking if some input is greater than a defined value. It should really only work with numeric values, but one of the challenges we need to work with is that our data is only provided to us as an object. As a result, we’ll have to do some type checking on our own.

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace LambdaRefactor.Processing.PreRefactor.Numeric
{
  public class GreaterProcessor : Processor
  {
    private readonly decimal _value;

    public GreaterProcessor(object mandatoryArgument, object value)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      _value = Convert.ToDecimal(value, CultureInfo.InvariantCulture); // will throw exception on mismatch
    }

    protected override bool Process(object importantReference, object input)
    {
      decimal numericInput;
      try
      {
        numericInput = Convert.ToDecimal(input, CultureInfo.InvariantCulture);
      }
      catch (Exception)
      {
        return false;
      }

      return numericInput > _value;
    }
  }
}

And to put a spin on things, let’s implement a processor that operates on string values only. We’ll implement the processor that checks if strings are equal. Like the GreaterProcessor, we’re forced to get object references passed in. We’ll need to convert these to strings to work with them.

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PreRefactor.String
{
  public class StringEqualsProcessor : Processor
  {
    private readonly string _value;

    public StringEqualsProcessor(object mandatoryArgument, object value)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      _value = (string)value; // will throw exception on mismatch
    }

    protected override bool Process(object importantReference, object input)
    {
      return Convert.ToString(input, System.Globalization.CultureInfo.InvariantCulture).Equals(_value);
    }
  }
}

Where can we go from here?

  • We can make simple inverse processors by overriding others and inverting the return value on the Process() function. Want a StringDoesNotEqual processor? It’s just as easy as ¬†inheriting from the StringEqualsProcessor and then modifying the return of Process(). Then we add this to our factory.
  • Adding other various types of processors is easy. We just have to extend our base class and add a couple of lines to our factory.
  • This code is much easier to test than one monolithic function that does all types of processing. We can now put a nice testing framework around this, and test each method on each class individually.

Post-Refactor: All of the Lambdas!

So… Why don’t we stop here? Because we can do better.

I mentioned that to make a simple inverse processor, all I had to do was override a class and invert the return value of Process(). That’s pretty easy to do… Except I need an entire new class to do it. If I want to make more types of numeric processing, I need to provide similar type checking and conversion. This code gets duplicated every time I go to add another simple class.

I also have my factory class responsible for creating my processor instances. They’re relatively coupled already, but I want developers to have to use my factory to construct instances of processor interface¬†and not worry about the specific implementations. So what if my factory had a bit more say in the construction if the processors? I could use lambdas to pass in the logic that’s unique to each type of processor, and keep each type of processor pretty bare bones. This would move more logic into the factory, but reduce the number of processor implementations I have to make.

So let’s do better!

Let’s start with our new IProcessor implementation. We’ll provide a delegate signature that will be the basis for the lambda expressions we pass in:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PostRefactor
{
  public abstract class Processor : IProcessor
  {
    private readonly object _importantReference;

    public Processor(object mandatoryArgument)
    {
      if (mandatoryArgument == null)
      {
        throw new ArgumentNullException("mandatoryArgument");
      }

      _importantReference = mandatoryArgument;
    }

    public delegate bool ProcessDelegate<T>(object importantReference, T processorValue, T input);

    public bool TryProcess(object input)
    {
      if (input == null)
      {
        return false;
      }

      return Process(_importantReference, input);
    }

    protected abstract bool Process(object importantReference, object input);
  }
}

From here, we can come up with some child classes that that are generic enough for us to work with using lambas that still provide enough functionality for them to exist on their own. We can break our processors up based on the type of data they’ll be working with. That is, we can have a processor for numeric values and a processor for string values. This will cover a lot of the duplicated functionality that exists in the current state of our refactor if we wanted to keep creating new IProcessor implementations.

Let’s start with our NumericProcessor:

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace LambdaRefactor.Processing.PostRefactor.Numeric
{
  public class NumericProcessor : Processor
  {
    private readonly decimal _value;
    private readonly ProcessDelegate<decimal> _processDelegate;

    public NumericProcessor(object mandatoryArgument, object value, ProcessDelegate<decimal> processDelegate)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      if (processDelegate == null)
      {
        throw new ArgumentNullException("processDelegate");
      }

      _value = Convert.ToDecimal(value, CultureInfo.InvariantCulture); // will throw exception on mismatch
      _processDelegate = processDelegate;
    }

    protected override bool Process(object importantReference, object input)
    {
      decimal numericInput;
      try
      {
        numericInput = Convert.ToDecimal(input, CultureInfo.InvariantCulture);
      }
      catch (Exception)
      {
        return false;
      }

      return _processDelegate(importantReference, _value, numericInput);
    }
  }
}

And similarly, a StringProcessor:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PostRefactor.String
{
  public class StringProcessor : Processor
  {
    private readonly string _value;
    private readonly ProcessDelegate<string> _processDelegate;

    public StringProcessor(object mandatoryArgument, object value, ProcessDelegate<string> processDelegate)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      if (processDelegate == null)
      {
        throw new ArgumentNullException("processDelegate");
      }

      _value = (string)value; // will throw exception on mismatch
      _processDelegate = processDelegate;
    }

    protected override bool Process(object importantReference, object input)
    {
      return _processDelegate(importantReference, _value, Convert.ToString(input, System.Globalization.CultureInfo.InvariantCulture));
    }
  }
}

With these two basic child classes built upon our new IProcessor implementation, we can restructure a new IProcessorFactory implementation. As I mentioned, we can leverage lambdas to move some logic back into the factory class and keep the processor implementations relatively basic.

Here’s the new factory:

using System;
using System.Collections.Generic;
using System.Text;

using LambdaRefactor.Processing.PostRefactor.Numeric;
using LambdaRefactor.Processing.PostRefactor.String;

namespace LambdaRefactor.Processing.PostRefactor
{
  public class ProcessorFactory : IProcessorFactory
  {
    public IProcessor Create(ProcessorType type, object mandatoryArgument, object value)
    {
      switch (type)
      {
        case ProcessorType.GreaterThan:
          return new NumericProcessor(mandatoryArgument, value, (_, x, y) => x <; y);
        case ProcessorType.StringEqual:
          return new StringProcessor(mandatoryArgument, value, (_, x, y) => x == y);
        /*
         * Look how easy it is to add new processors! Exercise for you:
         * implement the remaining processors in the enum!
         */
        default:
          throw new NotImplementedException("The processor type '" + type + "' has not been implemented in this factory.");
      }
    }
  }
}

As you can see, our new factory is simple like our first implementation. The major difference? We’re passing very simple lambdas that would have otherwise been functionality defined in a very light-weight child class. This allows us to move away from having many potentially very bare-bones classes and minimizes the amount of boilerplate duplication.

Summary

I didn’t post it here, but the original implementation that this example paralleled ¬†in real life was a pain to deal with. It was hard to test, brittle to modify/extend, and just downright unwieldly. It was obvious to me that switching to a refactored object-oriented implementation was going to make this style of code easy to extend and easy to test.

The initial refactor posted in this example was a great step in the right direction. The code became easy to build upon by relying on simple OOP principals, and granular parts of the functionality became really easy to test. If I just wanted to test certain types of numeric processing, I didn’t have set up a test for my entire massive “process” function. All I’d have to do is make an instance of the processor I want to test, and call the methods I’d like to cover. Incredibly easy.

Lambdas took this to the next level though. By leveraging lambads, I could refactor even more common code into a base class. This meant that ¬†in order to use my processors properly, the final factory class implementation definitely became required to use. It caused a paradigm shift where instead of making lots of light-weight child classes for additional processor implementations, I’d only need to implement some logic in the factory. All of my existing processors could be refactored into a handful of generic processor classes, and the factory would be responsible for passing in the necessary lambdas.

Lambdas let you accomplish some pretty powerful things, and this refactoring example was one case where they made code much easier to manage. Hopefully you can find a good use for lamba expressions in your next up-coming programming task!

Code Downloads


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress