Tag: development

What Makes Good Code? – Patterns and Practices Series

What Makes Good Code?

It’s been a while since I’ve had a programming oriented post, and I figured this would be a great topic to write about. It’s been a topic I’ve been thinking about more and more over the last year and I’ve been experimenting with certain patterns and practices to see if certain things actually make code “better”. A lot of the information presented in this series will be completely based on my opinion, but I’ll try to back up my opinion with as many concrete examples as I can. If you have a differing opinion, I’d love to hear it in the comments.

I’d also like to call out that much of what I’ll be discussing is in the context of object oriented programming. To be specific, there may be mostly C# examples used. If this isn’t something you’re actively doing, then don’t worry! It would be great to hear if you see parallels in the work you’re doing.

What Is “Good”?

So let’s start by defining what “good” or “better” means (and I’ll leave this high level and we can dive in afterwards)…

  • Extensible: Re-writing of code is minimized when adding more functionality. It feels straight forward to extend the code. Developers won’t do “the wrong thing” when trying to extend the code.
  • Maintainable: Many of the same qualities that go with extensible. Fixing bugs or making tweaks involves touching few places in the code base.
  • Testable: It’s straight forward to write coded tests that can exercise functionality of the code under test.
  • Readable**:  Developers should be able to read code and understand what it’s doing. The flow of execution within and between different modules of code shouldn’t cause anyone a headache,

All of these describe qualities of the code. I could argue that you could write very maintainable, extensible, and testable code and it would be awful if it didn’t actually solve the customers’ needs. I’d like to try and leave this aspect out of the discussion, and focus on the actual patterns/practices that we can implement in code. I’d love to write something separate about writing code that actually solves a problem versus code that may potentially solve some possible problem at some potential point in the future (and yes, all of the uncertainty in that sentence was on purpose).

Why Should We Care?

It’s kind of a funny question, I guess, but I think it’s a fair one to ask. Why should we care what good code is? If we agree on the definition of good code, so what? Maybe those criteria for good code are obvious to some people. Maybe they weren’t so obvious to some people, but they still don’t really care. So why the fuss about what good code is?

If you’ve read other posts on DevLeader or you know me personally, you may know that I started work at a digital forensics startup a few years back in Waterloo Ontario. What you may not know is that that startup has grown significantly, and based on the accolades we’ve received as an entire organization, we’re actually one of the fastest growing software companies in North America in terms of revenue. I’m not trying to do the horn tooting without a reason though… I think one of the reasons we’ve been able to have such great success on the development side of things is because we’re always trying to improve.

We didn’t always write “good” code, and we certainly don’t always write “good” code right now. However, we’re always trying to figure out how we can get better. So why might WE care as developers at our office? I think it comes down to trade-offs.

In the real world of software development, you’re often faced with trade-offs. You can get a product out faster if you don’t test it. Or you can get a product out and test it, but maybe you had to take a lot of shortcuts in the code. Or maybe you can get all the features in the product and tested, but you can’t hit the deadline. There’s countless more combinations of trade-offs that we make in real software development every day. I think that by understanding what “good” code means allows a team to recognize just what kinds of corners they’re cutting sometimes. When teams talk about introducing “tech debt”, there’s a better grasp around what type of debt you’re introducing. If you need to get some extra features and bug fixes in but they’re getting added with some tech debt, what could that end up meaning?

Even if you don’t agree with what my criteria are for good code, I think it’s important that you establish this within your team. If everyone can agree on what good code is, it makes constructive conversations about different implementations much easier. Just because some new code is different doesn’t instantaneously make it scary and/or wrong… Maybe it’s a new way that emphasizes one of the criteria for good code a bit more than another implementation might emphasize. Perhaps it doesn’t… You can at least refer back to a reference point for what “good” is.

It’s also important to recognize that the criteria for “good” may change over time. Revisiting the definition periodically might allow you to recognize when your team is redefining what “good” means to them.

Enough Rambling! Where’s This Going?

Right. Okay. I want to write some follow up posts that will focus on a few of the following items:

  • Does every class need an interface?
  • Does every class need a factory that can create it?
  • Unit tests versus functional tests
  • Is there a benefit to only passing interfaces to objects around?
  • Is there a way to enforce that interfaces HAVE to be passed around?
  • Is the single responsibility principle even helpful?
  • Mutability and immutability
  • Is it always good to follow patterns and practices in all scenarios?

And after I feel that I’ve covered enough on these topics, I’d like to circle back and revisit what “good” code is. It’ll be cool to see if the definition changes at all!

**Readability was an after thought and I’m not sure how… I started writing the first example post for this series and QUICKLY realized I had omitted this.


Yeah, We’re an “Agile” Shop

Everybody Has Gone “Agile”

If you’re a software developer that’s done interviews in the past few years, then you already know that every software development shop has gone agile. Gone are the days of waterfall software development! Developers have learned that waterfall software development is the root of all evil, and the only way to be successful is to be agile. You need to be able to adapt quickly and do standups. You need to put story point estimates on your user stories. You need retrospectives… And agility! And… more buzz words! Yes! Synergy! In the cloud! You need it!

Okay, so why the sarcasm? Every single software development team is touting that they’re following the principles of agile software development, but almost no team truly is. Is it a problem if they aren’t actually following agile principles? Absolutely not, if they’re working effectively to deliver quality software. That’s not for me to say at all. I think the problem is that people are getting confused about “being agile”, but there’s nothing necessarily wrong with how they’re operating if it works for them.

Maybe We’re Not So “Agile”

I work at Magnet Forensics, and for a long time now, I’ve been saying “yeah, we’re an agile shop”. But you know what? I don’t think we are. I also don’t think that’s a problem. I think our software development process is best defined by “continuous improvement”. That’s right. I think we’re a “Continuous Improvement” shop. Our team has identified the things we think work well for us in how we develop software, and we experiment to improve on things that we think aren’t working well. I’m actually happy that we operate that way instead of operating by a set of guidelines that may or may not work for us.

So, why aren’t we agile? When I look at the Agile Manifesto, I feel like there’s a few things we actually don’t do, and we don’t even worry about them. We don’t necessarily have business people working with developers daily through things, for example. Our delivery cycles are much longer than a couple of weeks most of the time. Sometimes people on our teams don’t communicate best face-to-face. I mean, just because we’re not focusing on those things isn’t necessarily proof that we aren’t agile, but I truly don’t think we’re trying to embody all of the components that make up agile.

As I stated previously, I do think that we try to focus on continuous improvement above all else, and I’m absolutely content with that. I think that if over time we continued our retrospectives and our team ended up operating closer to a traditional waterfall process then it would be the better thing for our team. Why? Because we make incremental changes for our team in an attempt to keep improving. Switching to waterfall is a bit of a contrived example, but I definitely stand by it. Another example might be that maybe working with business people daily isn’t actually effective for our team. I don’t know, to be honest, because we’re currently tweaking other parts of our development process to improve them. Maybe we’ll get around to worrying about that at some other point.

I do know that the way we operate, we’re always trying to improve. Whether or not we get better sprint to sprint is for the retrospective to surface for us, but if we took a step back, at least we can try a different path when we try to take our next step forward.

So, We Don’t Need To Be Agile?

I think my only point of writing this post was to get this across: If you’re not actually an agile software development shop, then don’t call yourself that. There’s absolutely nothing wrong with not living and breathing agile. Maybe you’re a software shop that’s transitioning into Agile. Maybe you’re moving away from Agile. Maybe you have no parts of your software development process that are agile. Who’s to say that because you’re not 100% agile your setup is bad?

I can’t advocate that agile software development is the absolute best thing for all software development teams. I personally like to think that it’s a great way to develop software, but… I don’t know your team. I don’t know your codebase. I don’t know your products, services, or clients. How the heck could I tell you the best way to go make your software?

Again, there’s nothing wrong with not being 100% agile, but we should try to be honest with ourselves. Find what works for your team. Find out how you can effectively deliver quality software.


Should My Method Do This? Should My Class?

Whose Job Is It?

I wanted to share my experience that I had working on a recent project. If you’ve been programming for a while, you’ve definitely heard of the single responsibility principle. If you’re new to programming, maybe this is news. The principle states:

That every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class

You could extend this concept to apply to not only classes, but methods as well. Should you have that one method that is entirely responsible for creating a database connection, connecting to a web service, downloading data, updating the database, uploading some data, and then doing some user interface rendering? What would you even call that?!

The idea is really this: break down your code into separate pieces of functionality.

Easier Said Than Done… Or Is It?

The idea seems easy, right? Then why is it that people keep writing code that doesn’t follow this guideline? I’m guessing it’s because even though it’s an easy rule, it’s even easier to just… code what works.

The recent experience I wanted to share was my work on a project that has a pretty short time frame to prove it was feasible. It was starting something from scratch, so I had all the flexibility in the world to design code however I wanted to. I really made an effort to keep asking myself this one question: Whose job is it?

Every time I asked that question and found that it was not my current method’s responsibility, I would ask “Is this class really responsible for that”? I’d either go make myself a new method in my class or I’d just go immediately make a new class with a single method on it. It seemed like a bit of extra overhead each time I had to do it, but was it worth it in the end?

Absolutely. After the project had proven itself and development continued on, I was easily able to refactor code (where necessary) and mock out functionality in my coded tests. Instead of trying to write test setup code that required a whack of classes I needed to initialize, I could mock out a couple of interfaces and test with ease. It was also really obvious which pieces were responsible for what functionality.

Final Thoughts

If you want to get better at following the single responsibility principle, I think it starts with one question: Whose job is it? Try it out!


Multiple C# Projects In Your Unity 3D Solution

Unity

Problem: Visual Studio and Unity Aren’t Playing Nice!

Disclaimer: I develop on Windows, so I have no idea if any of this even applies to other operating systems. I assume not. Sorry.

I just started poking around in Unity 4.6 and I’ve been having a blast. I’ve made it to the point where I want to actually start hammering out some code, but I came across a bit of a problem: I want to start leveraging other projects I’ve written in my Unity solution while I’m in Visual Studio, and things are blowing up. So, what gives?

Okay, so let me start by explaining why I want to do this. I understand that if I’m making a simple game, I should have no problem breaking out my unity scripts into sub folders and organizing them to be nice and pretty. The problem I’m encountering is that I have existing projects under source control and I don’t want to copy and paste all of the code as scripts into my Unity folder. I also want to be able to create re-usable code for my future games, so I’d like to start breaking things out into libraries as I see fit.

So, if you’ve been playing around in Unity for a bit, you might say “Oh, well you’re a dummy! Unity can totally leverage your C# DLLs once you drop them into your asset folder”! And you’d be 100% correct. But that’s not the workflow I want.

The underlying problem here is this: Unity will re-write your solution and project file when you flip between Unity and Visual Studio. But I’m sure they have it that way for a reason.

The Goal: Visual Studio and Unity Should… Play Nice!

My ideal state would be something like this:

  • Work in visual studio as much as I’d like to new projects to my solution, and reference them accordingly
  • Flip back and forth from Unity and Visual Studio without having to reset things to compile/run again
  • Build from visual studio and have things end up in the right spot… NOT copy DLLs
  • Not copy+paste my entire project(s) already under source control elsewhere

Is this something that can be achieved though? I was pretty determined that I should be able to do *something* to have this working. Could I get it perfect? I wasn’t sure… But I knew I could make it better.

The Solution: Give and Take with Unity

My *almost* perfect sution, which I’ll walk you through, is this: Leveraging Visual Studio tools for Unity, modify the Unity solution as you see fit and use directory junctions (symlinks) to the build output directories of other projects.

  1. Let’s get Visual Studio tools for Unity installed. Visit that link and download the version that you need for the version of Visual Studio that you use. After installing, I opened up my project within Unity and I had to import the Visual Studio Tools package.Import Package
    After selecting this menu item, I was presented with a dialog for picking the items to import. I left it as is.Import Package2After importing these items, I could see that Unity had successfully added these entries under my Assets folder. Okay, now we’re getting somewhere. Next up, I wanted to configure Unity to not modify my solution every time I go back and forth from Unity to Visual Studio. This is the part that kills whether or not I’ve added projects to my solution. For me, it’s critical to have code I’m working on immediately accessible so that I can jump back and forth between projects. Lucky for us, this part is pretty easy. Go to the menu to access your new Visual Studio Tools menu item:

    VS Tools Configure
    Selecting “Configuration” opens up a really simple dialog. Let’s make sure “Generate solution file” is unchecked! It’s that easy.

    VS Tools Configure2
    Once we have all of this setup, we should be able to go into Visual Studio and add other projects to our solution.

  2. The one thing that I *could not* get this solution to do is have Unity leave my main game project alone in Visual Studio. As a result, the rest of this walk through is allowing us to play by Unity’s rules. Unity is good at magically referencing all of the managed DLLs that you include within your assets folder. If you drop DLLs somewhere within “Assets” and switch to Visual Studio, Unity will likely have modified your main project to reference this DLL.My next step was creating a spot where I wanted to drop the build outputs of my extra projects I wanted to reference. In my Visual Studio solution, I have my original game project and some newly added projects I want to build from source. In Unity, I wanted these to end up in “Assets/Dependencies/bin”. No problem. Let’s make that folder structure (or your equivalent if you don’t like my naming):Bin Dependencies
    The next part is probably the “trickiest” part because it’s… well… unusual. You could technically stop here and manually copy DLLs back and forth, but I’m not about that life. I want things to happen automatically. For this, we’re going to use junction points. Browse to your newly created folder in an administrator command prompt. I say administrator because only certain users have permissions to create junction points. Your non-admin user might, but this is my “safe” way of instructing you. On the command prompt, we’re going to use “mklink” to create a junction. The command is “mlkink /D /J <NAME_OF_YOUR_PROJECT> <RELATIVE_PATH_TO_YOUR_PROJECT>”. For example, if you had a C# project you wanted to reference that was “MyCoolLibrary.csproj” and was located in the directory above your Unity project, you might use the command “mlkink /D /J MyCoolLibrary “……..MyCoolLibrarybindebug””. Note that I used two dots to go back up a directory several times (since we’re inside of AssetsDependenciesbin and want to get outside of our Unity project). you should get a success message when your junction is created.

    Repeat this step for as many extra projects as you want to include. You can always come back and add more projects this way too, or remove the junctions if you don’t want to include a project anymore.

    At this point, you’re technically done. If you build from Visual Studio, you should have your other projects’ DLLs end up in your Unity folder, and your main game project will be updated by Unity to reference these now!

  3. But… You’re not done if you use source control for your Unity project and have separate source control on your other projects. The scary thing here is that usually we don’t want our build outputs to be stored in source control… But if we do nothing else, your source control system will likely want to include the newly created “AssetsDependenciesbin” folder and any of the contents you’re building into there. I just modified my git ignore file (I’m sure there’s an equivalent for SVN or other source control) to exclude the contents of “AssetsDependenciesbin”.The reason I didn’t excluded dependencies all together is because I can add other folders and DLL references here that I don’t want to build (like… the normal way). This gives me the flexibility of building the projects I want to control and still be able to just reference other pre-built DLLs!

Summary

In three easy steps, you should be able to use Unity, Visual Studio, and multiple projects in one solution in a what-feels-like-normal way. Because there’s still some dynamic stuff going on with Unity updating your main project, you might find the odd time you need to build twice to fix up compilation problems. I’ve seen this happen maybe once or twice so far, but otherwise it feels like normal. It’s also  important to note that you can’t escape the Unity project updating… don’t add references to your main project manually. That’s what that “AssetsDependencies” folder is for that we made.

Here are a few shots of what my setup looks like (proof that it works):

Solution Explorer

Unity Dependencies

And of course… it’s not the perfect solution. There’s still these things:

  • Unity gets mad at you for using junctions within your project. It actually tells you not to do this because you can mess things up. It’s working awesome for me right now though… So I’m going to just ignore this warning.
  • Remember step 3 where we ignored the AssetsDependenciesbin location in git? This actually ignored your junction points you created too. As a result, anyone else who clones your code will need to create junctions too. I’m working solo, so I’m not too worried about this step… But it’s definitely something that should be fixed up (again, I’m sure it’s doable, but I’m in no rush).

Hope that helps you feel more at home in Unity and Visual Studio! It certainly made it nicer for me.

 


ProjectXyz: Enforcing Interfaces (Part 2)

Enforcing Interfaces

This is my second installment of the series related to my small side project that I started. I mentioned in the first post that one of the things I wanted to try out with this project is coding by interfaces. There’s an article over at CodeProject that I once read (I’m struggling to dig it up now, arrrrrghh) that really gave me a different perspective about using interfaces when I program. Ever since then I’ve been a changed man. Seriously.

The main message behind the article was along the lines of: Have your classes implement your interface, and to be certain nobody is going to come by and muck around with your class’s API, make sure they can’t knowingly make an instance of the class. One of the easiest ways to do this (and bear with me here, I’m not claiming this is right or wrong) is to have a hidden (private or protected) constructor on your class and static methods that let you create new instances of your class. However, the trick here is your static method will return the interface your class implements.

An example of this might look like the following:


public interface IMyInterface
{
    void Xyz();
}

public sealed class MyImplementation : IMyInterface
{
    // we hid the constructor from the outside!
    private MyImplementation()
    {
    }

    public static IMyInterface Create()
    {
        return new MyImplementation();
    }

    public void Xyz()
    {
        // do some awesome things here
    }
}

Interesting Benefits

I was pretty intrigued by this article on enforcing interfaces for a few reasons and if you can stick around long enough to read this whole post, I’ll hit the cons/considerations I’ve encountered from actually implementing things this way. These are obviously my opinion, and you can feel free to agree or disagree with me as much as you like.

  • (In theory) it keeps people from coming along and tacking on random methods to my classes. If I have an object hierarchy that I’m creating, having different child classes magically have random public APIs changing independently seems kind of scary. People have a harder time finding ways to abuse this because they aren’t concerned with the concrete implementation, just the interface.
  • Along with the first point, enforcing interfaces makes people think about what they’re doing when they need to change the public API. Now you need to go change the interface. Now you might be affecting X number of implementations. Are you sure?
  • Sets people up nicely to play with IoC and dependency injection. You’re already always working with interfaces because of this, now rolling out something like Moq or Autofac should be easier for you.
  • Methods can be leveraged to do parameter checks BEFORE entering a constructor. Creating IDisposable implementations can be fun when your constructor fails but and your disposable clean up code was expecting things to be initialized (not a terribly strong argument, but I’ve had cases where this makes life easier for me when working with streams).

Enforcing Interfaces in ProjectXyz

I’ve only implemented a small portion of the back-end of ProjectXyz (from what I imagine the scope to be) but it’s enough where I have a couple of layers, some different class/interface hierarchies that interact with each other, and some tests to exercise the API. The following should help explain the current major hierarchies a bit better:

  • Stats are simple structures representing an ID and a value
  • Enchantments are simple structures representing some information about modifying particular stats (slightly more complex than stats)
  • Items are more complex structures that can contain enchantments
  •  Actors are complex structures that:
    • Have collections of stats
    • Have collections of enchantments
    • Have collections of items

Okay, so that’s the high level. There’s obviously a bit more going on with the multi-layered architecture I’m trying out here too (since the hierarchies are repeated in a similar fashion in both layers). However, this is a small but reasonable amount of code to be trying this pattern on.

I have a good handful of classes and associated interfaces that back them. I’ve designed my classes to take in references to interfaces (which, are of course backed by my other classes) and my classes are largely decoupled from implementations of other classes.

Now that I’ve had some time to play with this pattern, what are my initial thoughts? Well, it’s not pure sunshine and rainbows (which I expected) but there are definitely some cool pros I hadn’t considered and definitely some negative side effects that I hadn’t considered either. Stay tuned

(The previous post in this series is here).


Continuous Improvement – One on One Tweaks

Continuous Improvement - One on One Tweaks

Continuous Improvement – Baby Steps!

Our development team at Magnet Forensics focuses a lot on continuous improvement. It’s one of the things baked into a retrospective often performed in agile software shops. It’s all about acknowledging that no system or process is going to be perfect and that as your landscape changes, a lot of other things will too.

The concept of continuous improvement isn’t limited to just the software we make or the processes we put in place for doing so. You can apply it to anything that’s repeated over time where you can measure positive and negative changes. I figured it was time to apply it to my leadership practices.

The One on One

I lead a team of software developers at Magnet, but I’m not the boss of any of them. They’re all equally my peers and we’re all working toward a common goal. One of my responsibilities is to meet with my team regularly to touch base with them. What are things they’ve been working on? What concerns do they have with the current state of things? What’s going well for them? What sort of goals are they setting?

The one on ones that we have setup are just another version of continuous improvement. It’s up to me to help empower the team to drive that continuous improvement, so I need to facilitate them wherever I can. Often this isn’t a case of “okay, I’ll do that for you” but a “yes, I encourage you to proceed with that” type of scenario. The next time we meet up, I check in to see if they were able to make headway with the goals they had set up and we try to change things up if they’ve hit roadblocks.

No Change, No Improvement

I had been taking the same approach to one-on-ones for a while. I decided it was time for a change. If it didn’t work, it’s okay… I could always try something else. I had a good baseline to measure from, so I felt comfortable trying something different.

One on ones often consisted of my team members handing me a sheet of past actions, concerns, and status of goals before we’d jump into a quick 20 minute meeting together. I’d go over the sheet with them and we’d add in any missing areas and solidify goals for next time. But I wanted a change here. How helpful can I be if I get this sheet as we go into the room together?

I started asking to get these sheets ahead of time and started paraphrasing the whole sheet into a few bullet points. A small and simple change. But what impact did this have?

Most one on ones went from maxing out 20 minutes to only taking around 10 minutes to cover the most important topics. Additionally, it felt like we could really deep dive on topics because I was prepared with some sort of background questions or information to help progress through roadblocks. Myself and my team member could blast through the important pieces of information and then at the end, if I’d check to make sure there’s nothing we’d missed going over. If I had accidentally omitted something, we’d have almost another 10 minutes to at least start discussing it.

Trade Off?

I have an engineering background, so for me it’s all about pros and cons. What was the trade-off for doing this?

The first thing is that initially it seemed like I was asking for the sheets super early. Maybe it still feels like I’m asking for them early. I try to get them by the weekend before the week where I start scheduling one on ones, so sometimes it feels like people had less than a month to fill them out. Is it a problem really? Maybe not. Maybe it just means there’s less stuff to try and cram into there. I think the benefit of being able to go into the meeting with more information on my end can make it more productive.

The second thing is that since I paraphrase the sheet, I might miss something that my team member wanted to go over. However, because the time is used so much more effectively, we’re often able to cover anything  that was missed with time to spare. I think there’s enough trust in the team for them to know that if I miss something that it’s not because I wanted to dodge a question or topic.

I think the positive changes this brought about have certainly outweighed the drawbacks. I think I’ll make this a permanent part of my one on one setup… Until continuous improvement suggests I should try something new!


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 SucksJoaquin 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 LearntChristophe 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!


  • 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