Tag: tips

Recognition – Weekly Article Dump

Recognition - Weekly Article Dump (Image from http://www.sxc.hu/)

Recognition – Weekly Article Dump

Not all of the articles this week touch on recognition, and to be honest, I didn’t pick it as a theme for the articles either. Recognition is more a topic of discussion that’s come up over the last week at Magnet Forensics, where I work. Being a team lead and part of the management team at Magnet, I’m often part of conversations about motivation. Providing recognition is an excellent way to motivate your staff and shows that you truly appreciate them. We’ve been trying to get better at recognizing staff for doing an awesome job–especially because we have so many awesome people working with us. It’s pretty obvious with our Profit Hot 50 placement that we’ve got some kick-ass people.

Recognition, whether it’s one-on-one or in a public setting, has a huge impact. I don’t even mean recognition in the form of compensation (e.g. bonus or salary raise). Just giving someone recognition for the awesome work they’ve done–plain and simple. It’s a great way to let someone know that their hard work and commitment isn’t going unnoticed. Sure, if they’re developing products, making sales, or acquiring leads there are certain metrics that indicate they’re doing a great job, but recognition is that additional feedback you can provide to really drive the point home. It motivates people and often has a bigger impact than providing compensation.

I want to make a conscious effort to try and recognize some of my colleagues on Dev Leader, going forward, when the opportunity presents itself. I’m always learning from the people I work with and there’s always something great I can say about them. Why not give them a public acknowledgement?

I also have a little surprise coming from a friend and colleague of mine, Tayfun Uzun, early next week, so keep your eyes open for that!

Articles

  • Job Titles and Responsibilities: Last week I wrote about my thoughts on the true role of job titles. As soon as you start to look at your job title as something that defines your limits, you’re on the wrong path. Your job title should define what you’re responsible for, but it’s by no means supposed to put limits on what you can do. Check it out and let me know what you think! Do you feel like job titles should keep people to only a certain set of tasks? Do you feel like having set responsibilities is useful at all?
  • How Strong Is Your Bench: Having a successful company is all about having the right people on board. Sylvia Hewlett writes about what it means to have a rock solid roster within your company. Some of the things include avoiding hiring clones of people exactly like yourself and instead trying to diversify the skill sets within your company. Absolutely true!
  • 8 Steps for Engineering Leaders to Keep the Peace: There seems to be a natural tendency for engineers or people implementing components of a product to push back on product managers or people who decide how a product/service should be. Steven Sinofsky discusses the importance of being an effective engineering leader and ensuring proper communication between engineering leaders and people like PMs or founders. Open and transparent communication is key and helps remind the other party that you do in fact have the same end-goal.
  • Top Tips To Being a Great Mentor: In this article, James Caan provides four key points for being a better mentor. Patience, honesty, positivity, and focus are the four pillars that James describes. Patience and honesty, in my opinion, are the most important but I certainly agree with all four!
  • Leading a Customer-Centric Transformation: Hopefully it’s not surprising, but customers are what your business should be geared toward. As a result, it makes sense that leading customer-centric employees would be beneficial. Don Peppers outlines six things to focus on to make this transformation necessary. It ties in with my post on avoiding organizational silos.
  • The Dark Side Of Software Development That No One Talks About: Don’t be scared that this article mentions software development if you’re not a programmer! It touches on some great points about having a career in software development, so even if you’re not a developer yourself, it sheds some light on some more broad issues. John Sonmez writes about why software developers seem like jerks sometimes and what you can do about it. It seems to boil down to intelligence being a deciding factor for how well you program, so lording your intelligence over other people makes you superior. And because our own intelligence is something we all hold personally, we can get defensive about it pretty easily. John suggests that part of the solution is trying to simplify aspects of software development.
  • How to Win Loyalty From Other People: To be a successful leader, the people you lead need to be loyal to you. Deepak Chopra writes about seven suggestions for building up loyalty and among them “abstaining from disloyalty” is one of my favourites. If you act differently behind people’s backs compared to when you’re leading them, it may come back to bite you later. It’s also crucial to pay attention to each individual’s personal differences to ensure they feel understood.
  • Strategies for Dealing with Randomness in BusinessDon Peppers twice on the list this week! Things in life and business aren’t always predictable for us. It’s just how things are. Are you properly set up to deal with uncertainty in your business though? Remain agile!
  • 10 Quotes All Entrepreneurs Should Memorize: How about some quotes to motivate you? Joel Peterson lists 10 great quotes for entrepreneurs, but I think they carry over to anyone working in a startup. Don’t be afraid to fail and keep moving forward to improve!
  • The Two Biggest Distractions – And What to Do About Them: Distractions are ever-increasing in the workplace, but have you ever considered the differences between the different types of distractions? Daniel Goleman discusses two very different types of distractions: sensory and emotional. I hadn’t really noticed it, but often we find ourselves consciously trying to avoid sensory distractions. If our phone lights up or we get an email notification, we either give in or we make an effort to try and reduce the effect of these distractions. But an emotional distraction is much worse. If something tweaks your emotions the wrong way at work, it often has a bigger impact and it’s usually unexpected.

My take away point for this week regarding recognition: Do it early and do it often. 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+

You can also check out Dev Leader on FlipBoard.


Raspberry Pi + WordPress => PiPress

Raspberry Pi

Background

In the past, I’ve dabbled a bit with hosting my own server on a spare outdated box that likely should have been thrown out. My least favourite thing to do is sit down and tinker with trying to get services and such configured so that they all work together… But once it’s working, it’s glorious. Enter the Raspberry Pi.

Earlier this year I decided I wanted to get a Pi. Why? I wasn’t too sure… But they’re cheap and nothing bad could come of it 🙂 Once I got the thing up and running I was reading about how people were using them. Hosting a WordPress site was definitely one of the uses, so I figured I’d try my hand at that. There are other guides on The Internet about how to do this, but this is what got me up and running.

Disclaimer: A *lot* of this is taken from IQ Jar where there’s been an absolutely amazing outline posted. Although I am repeating a lot of the same steps here, I wanted to post what I felt was a complete install guide. I found myself going back and forth between a few resources, so hopefully this will reduce that issue for you. I do very highly recommend you have a look at IQ Jar though.

Raspberry Pi: What & Where To Buy?

This part is pretty open ended. Let’s start with the “what” portion of things.

The Raspberry Pi is just the board. If you’re totally content with buying a board without a case that you can’t even power up, then you’re all set. Although, if that’s the case, you probably don’t need to read anymore of this! It’s common to pick up the following to get your Raspberry Pi working:

  • Raspberry Pi
  • Case
  • Power Adapter
  • SD Card

But once you’ve got those things, you still can’t do too much with your Raspberry Pi aside from powering it up. Some other things you’ll likely want:

  • USB Wireless Adapter
  • USB Keyboard
  • HDMI Cable

NOTE: Pay special attention to what wireless adapters and SD cards can be used with a Pi out of the box. You’ll want to save yourself the headache if others have confirmed the parts you’re looking at purchasing are compatible.

So now that you have an idea what things you’ll need to pickup, where do you get them? If you search The Googles for where to buy any of this stuff, you’ll probably get a ton of hits. Maybe that’s not totally useful for you. I’d suggest the following sites:

  • Amazon: I got everything I needed off of Amazon in one fell swoop. You can even find some combo deals that include the Raspberry Pi and a case. Heck, some even come with the SD card too!
  • ModMyPi: A great resource… There’s tons of options on this site and it’s specifically for the Pi. Probably can’t go wrong by looking here.
  • Ebay: Ol’ Faithful. Lots of options here too, just like Amazon. Bound to find something that fits the bill.
  • Newark: There are a great deal of product offerings and resources on Newark. Check them out for full packages, accessories, and additional guides/walk-throughs.

The Walkthrough

First thing: there are a million ways to do this. I’m not going to explore all the options here because I’m not an expert and because I want to provide you with my own steps that worked for me. As soon as I deviate from that… Things will get messy and complicated 🙂

  1. Download a Raspbian “Wheezy” image from the Raspberry Pi website. This is the image of the operating system your Pi will use.
  2. Download Win32 Disk Imager. You’ll need this to get the image of the operating system onto your SD card.
  3. Once both downloads have completed, run Win32 Disk Imager and use it to write the image to your SD card. You’ll need a card reader/writer in your computer, but this is pretty standard these days.
  4. Take your card out of your computer and pop it into your Pi. You should have your Pi all setup now with power, USB keyboard, USB WIFI adapter, and an HDMI cable plugged into your TV/monitor.
  5. When you power up your Pi, you should be taken to an initialization/configuration menu. If it ain’t working, there are a million and one trouble shooting guides.
  6. Some things I suggest you get going while you’re here:
    • Reduce graphics memory to the minimum (16). Should help with performance.
    • Give yourself a modest overclock. Not sure what’s deemed safe, but I went somewhere in the middle.
    • Enable SSH. Later on you’ll never even need to be near your Pi. I can actually control my Pi from my phone with this sweet app.
  7. Once you’ve got things how you want, expand the file system and reboot your Pi.
  8. When the Raspberry Pi is back up and running, you need to login to your credentials and then type “startx” and press enter. This will get you into the GUI portion of things.

Anyone well versed in *nix may not need or want to do this, but I found it easiest this way. At this point, get your wifi and everything setup. Your blog won’t be very useful if your Pi isn’t on the internet. Having the GUI portion of Raspbian will also let you quickly search the net and pull up articles if you’re running into any oddities with the components you bought. Anyway, now that your Raspberry Pi is working with all the parts you purchased, on with the rest of it:

  1. Open up a terminal. You’re going to need it for basically everything else in this guide. We’re going to start by turning your Raspberry Pi into a LAMP server.
  2. Type “sudo apt-get update” to update the various packages on your Pi.
  3. sudo apt-get install apache2” to download and install the Apache web server. You’ll want to say yes when it asks for confirmation (and same whenever this happens for the other packages we need to install).
  4. sudo nano /etc/apache2/apache2.conf” to open up the apache configuration. You’ll want to stick “ServerName localhost” at the very end of this file and then save and exit the editor. This will get rid of warnings about determining the server’s domain name.
  5. Restart apache by using “sudo service apache2 restart“. Amazing. You now have a web server.
  6. You’ll need to take care of any port forwarding to make sure your router does it’s job to get to your Pi.
  7. Next is installing PHP: “sudo apt-get install php5
  8. Type “ls /usr/lib/php5/” and take not of the entry that looks like “20100525+lfs“. Yours might be slightly different.
  9. sudo nano /etc/php5/apache2/php.ini” to open up the PHP configuration. Find the line that starts with “extension_dir” and change it so it looks like: extension_dir = “/usr/lib/php5/20100525+lfs/” (except with the name of the entry you have if it was different!)
  10. sudo nano /etc/apache2/apache2.conf” to open up the apache configuration. You want to verify you have this line in there: Include conf.d/*.conf
  11. Next up, you’re going to need to make a config file for Apache. This can be done by typing: “sudo nano /etc/apache2/conf.d/php.conf” and then putting the following text inside of the file:
    # PHP is an HTML-embedded scripting language which attempts to make
    # it easy for developers to write dynamically generated webpages.
    LoadModule php5_module modules/libphp5.so
    #
    # Cause the PHP interpreter to handle files with a .php extension.
    AddHandler php5-script .php
    AddType text/html .php
    #
    # Add index.php to the list of files that will be served as
    # directory indexes.
    DirectoryIndex index.phpSave and close nano when you’ve finished.
  12. To improve the performance of PHP, install APC by typing “sudo apt-get install php-apc
  13. Now that you’ve finished that, restart Apache: sudo service apache2 restart

Next we need to get MySQL up and running. This is going to serve as the backend for your WordPress installation.

  1. sudo apt-get install mysql-server mysql-client
  2. Follow up with the MySQL plugin for PHP: “sudo apt-get install php5-mysql
  3. Now that you’ve finished that, restart Apache: sudo service apache2 restart

Next we’re actually going to install wordpress!

  1. In your terminal: “sudo wget http://wordpress.org/latest.tar.gz
  2. Then extract the whole thing: “sudo tar -zxvf latest.tar.gz
  3. From here, you can either follow along with the official WordPress Setup instructions, or just do what I did. If you want to do what I did, just keep following here!
  4. We need to make a user in MySQL:
    1. In the terminal: “mysql -u <YOUR_ADMIN_USERNAME> -p” and hit enter.
    2. (Obviously where it says <YOUR_ADMIN_USERNAME> you should replace with the database admin username you picked)
    3. Enter your password as the prompt suggests and press enter.
    4. Next up: “CREATE DATABASE wordpress” to make the database named wordpress.
    5. And now we set privileges: “GRANT ALL PRIVILEGES ON wordpress.* TO “wordpress”@”localhost” IDENTIFIED BY “<YOUR_PASSWORD>”;” and press enter.
    6. (Again, it’s hopefully obvious to replace <YOUR_PASSWORD> with your password)
    7. FLUSH PRIVILEGES
    8. And then finally “EXIT
  5. For my install, I put WordPress right at the root of my website. To do this, we need to copy the contents of the wordpress directory to your /var/www/ directory, but we’re *NOT* copying the wordpress directory itself there: “cp -a wordpress/. /var/www/
  6. And now, we run the install script! Since we installed WordPress to the root of the website, we go to http://127.0.0.1/wp-admin/install.php in a browser. Follow the few simple steps there and you should be up and running!
  7. Remember to check the troubleshooting section on the WordPress site if something seemed to go wrong!

That’s it! You should be up and running.

What’s Next?

You might find your site is a little slow. That’s somewhat expected on your little Rapsberry Pi. Don’t fret. There are lot’s of methods for optimizing your site.

  • Check out WP Super Cache, or specifically, the guide over at IQ Jar for more information on tweaking this (it’s near the bottom of the post).
  • There’s minifying plugins for javascript and CSS files. This can do a nice job compressing the files and reducing how much data has to be transferred.
  • You can look at something like Smush.it to help with compressing your images that you serve. Again, smaller means faster.
  • Finally, you might want to test your site on GTmetrix to see if it can recommend any other optimizations to you.

Summary

To wrap up, I hope you found this guide informative. I thought a Raspberry Pi was a great way to start a little DIY project at home and it was fun to get a blog up and running on it.

References

I’m sure I consulted a million and one guides on the Internet, but the following that stick out to me (and I highly recommend you look into them):

  • IQ Jar: Crucial for getting me up and running. Specifically, these two guides here and here.
  • WordPress.com: The detailed guide here for installing WordPress once you have all the prerequisites was definitely necessary.
  • GTmetrix:  Serving content was relatively new to me. Once I was analyzing my page with this site, I was lead down a rabbit hole of different things to try and optimize. I highly recommend it!

Cookie Cutters For Projects

Background

When you’re starting work on a new project or organizing a team to accomplish a goal, there’s often a foundation that needs to be established:

  • How is your team structured?
  • What software should we use to help us?
  • How do we set goals?
  • How do we measure our progress
  • … the list goes on.

It’s a common challenge that’s met by anyone organizing a team or setting off to work on something. So do you copy what worked for someone else by using a cookie cutter approach, or do you wing it and see what happens? My approach when faced with two extremes is usually to aim somewhere in the middle.

 

Cookie Cutters

Being a copy-cat and using cookie cutters has some benefits. If something worked for some all-star teams at big successful companies, then why re-invent the wheel? They’ve proven that they have a process that works!

Look at a successful company that’s the same size as yours. Look at a team that’s completed a project that has a lot of parallels to what you’re going to be working on. How did they structure their team? Did they split off into smaller sub teams? Did they have daily meetings to discuss progress? Weekly? Monthly? Are they using some sort of software to assist them in their work? Maybe it’s a ticket tracking software, or some CRM to aid with customer interaction. If it worked for them, why wouldn’t it work for you?

The answer to that is because you aren’t them, you’re not working on the same project, and despite all the parallels you might see, your environment is different.

 

From Scratch

Okay okay… So if we can’t copy people, then let’s just do it all from scratch. Start your project tomorrow by holding a meeting and seeing who wants to work on what. Let people just start tackling parts of the project. Have someone create some software that will help you in accomplishing your goal (after all, you don’t want to copy someone else and use some well-established software). And now that you’ve all set off on working on parts of the project, you should probably just meet whenever you need to. Probably not best to schedule anything, because you don’t even know if you need to meet!

So, that sounds pretty sketchy, right? Clearly doing everything from scratch doesn’t seem ideal… Why re-invent the wheel on things that have been proven to work? Where’s the happy medium?

 

The Happy Medium

The truth is there are aspects to tackling a challenge with a team that have been proven to work. There are processes out there that teams have used successfully, software that has improved team efficiency, and strategies for gauging progress that have been used effectively. So when do you copy and when do you work from scratch?

My personal recommendation is to evaluate your options from the start. Look at what other successful companies are doing. Do they use a waterfall approach to developing products, or are they agile? Are they using particular software products for tracking progress, managing projects, interacting with customers, and/or automating processes? Make a list of those too. How often do they meet with other team members? Why are they meeting at those intervals? What are the pros and cons?

After you come up with your options, start gauging how they might apply to you. Your customer requirements are set in stone for your enormous project? Maybe a waterfall approach is better than being agile. Everyone on your team has success using Git and bad experiences using subversion for their source code… So maybe you start with that. Maybe tasks are changing pretty frequently and it’d be helpful to have frequent updates from team members, so you meet briefly every day for updates. Look at your options and think of why certain ones might be good for you.

Start with something. Try it out. There’s no guarantee you’re going to be right the first time you try things out. Actually, it’s likely you’ll do it wrong. But so what? Find out what works. Find out what doesn’t. Then figure out why something didn’t work, and swap that process for something else. Swap that software for something that fits your needs better. Change what doesn’t work and you’ll converge to a rock solid foundation. But don’t fix what isn’t broken. If your daily meetings have been working well for everyone, then why bother arbitrarily switching them to weekly? If it works, then use it.

 

Summary

Regardless of your approach to getting your challenge completed, I think one thing is important: Have flexibility in your foundation until you find what works. Don’t use certain things because other people say to. Use what you think might work best after you’ve evaluated your options, and then once you’ve had it in place for some time, change what doesn’t work. Use the cookie cutters as a source of information and inspiration for why you might want to try something, but don’t let your entire foundation be built from one big cookie cutter. Use lots of little cookie cutters to make your foundation for overcoming your challenge the best it can be for your team and not someone else’s.


Thread vs BackgroundWorker

Background

There are two classes available in the .NET framework that sometimes have some confusion around them: The Thread and the BackgroundWorker. They’re both used to do some heavy lifting for you on a separate thread of execution (so you can keep on keepin’ on), so why do we have two different things to accomplish the same end result

 

Enter The Thread Class

The Thread class is available in the System.Threading namespace. Surprising, right? It’s the basic unit for spawning off work to be done. Threads let you provide them with a name, which could be one advantage to using them. A thread can either operate as “background” which means it will be killed when the application exists, or not as background, which will actually keep the application alive until the thread is killed off.

An instance of the Thread class is relatively lightweight. It’s quick to set up for developers and all you need to do is provide it a method to run. You can put a loop in your thread body to keep it alive and do all sorts of fun stuff. Threads are great for setting up queuing, dequeing, scheduling, monitoring, receiving, and listening logic. Well, there are really countless uses for them, but those are some of the big ones I find I do a lot of.

 

Enter The BackgroundWorker

The BackgroundWorker class is available in the System.ComponentModel namespace. This is slightly different from the Thread class already, and for what it’s worth, I generally only have this namespace around if I’m dealing with a UI. That is, if I’m in the equivalent to a data layer or application layer, I usually don’t have these guys around (usually, but not necessarily always). So is that it then? Just the namespace is different?

The BackgroundWorker class is essentially built on top of the Thread class. The Thread part of the BackgroundWorker is sort of hidden from you. You get to work with two very important parts of the BackgroundWorker though, the DoWork and RunWorkerCompleted events (There’s a progress one too, but because I actually don’t use this much I’ll omit it for you to take on as homework). So… What are these events all about?

The DoWork event is invoked on a separate thread. This is where you want to do your heavy lifting, and you can pass in any object you want when you start up the BackgroundWorker–Simply pull it off of the event args in your DoWork event handler and cast it back to the necessary type. Presto! The RunWorkerCompleted event is what’s triggered when your DoWork event handler finishes up… but the big difference here is that RunWorkerCompleted runs on the thread that started the BackgroundWorker. This is extremely important when you’re working with UIs. Why? Because of cross thread exceptions! UI stuff is generally only run on the UI thread and nothing else. It’s important to note that the DoWork event handler can pass more state to the RunWorkerCompleted event handler by setting a result property on the event args. The RunWorkerCompleted event handler can then take advantage of this data!

My Guidelines

In the end, both of these classes can be used to do work on a different thread than the one you’re currently on. That’s great news. So what are my guidelines for picking one over the other?

  • If you have a long running task that persists, or perhaps something that is running that conceivable have stop/running/paused states (regardless of whether or not you implemented them) you may want a Thread.
  • If you have a task you want to run with the result handled and cleaned up afterward (i.e. a clear distinction between go do this stuff and let me handle the result) then you may want a background worker.
  • If you have a task to be done that you don’t want to block the UI but want to show the result afterward (i.e. loading tons of data to put in a list) then you probably want a background worker.

 

Summary

Threads and background workers can often be used to accomplish the same thing: offloading work to be done on a different thread of execution. I’ve tried to provide my own personal guidelines for when to use either, but there is no law to stop you from doing it as you see fit. As long as you understand what either option provides you, you can make your own decision based on your needs.


How and Why to Avoid Excessive Nesting

Background

This probably sounds really nit-picky or OCD, but I think it’s an issue worth addressing. Excessive nesting of logic within code can make things nightmarish to read. Even a few of years ago I never thought anything of this. I mean, how much could it really affect someone reading it? He/she must be a complete newb to not be able to read my logic. Fast forward to a co-op placement where this was more closely moderated by my managers, and I began to pay more attention to it…

Why?

Alright, so all that you know so far about my opinion on this is that excessive nesting bothers me. So far, my mission is accomplished. Everything else is just extra. The first issue with excessive nesting is that it actually makes logic hard to follow. If you’re doing code reviews or revisiting your old code, large methods that have lots of nested if statements and loops actually become a tangled mess of logical workflows. You don’t need to believe me yet, but I’m hoping by the end of this you might change your mind.

The next thing, and it’s related, is that it makes refactoring code quite tricky. If you have lot’s of deeply nested if statements, switching up the behaviour of a function even a little bit could have your mind warping with how to tackle all the logical branches. Have fun. Remember that one monolithic function that nobody wanted to go back and refactor? Well, it turns out you need to pass in another parameter now and handle it in all of your separate logical paths. Hold back the tears when you’re trying to recall the logic once you’re 10+ levels deep into nested if statements.

Another key point I’d like to mention is that, in my opinion, the larger the vertical separation between a conditional check and it’s bodies (i.e. the if block and the else block) the more difficult it becomes to read the code. Of course, this may not be a law or an all-the-time thing, but it’s certainly a decent guideline. Think about it though. If you have an enormous block of code for your if statement body, by the time you finish understanding that, you have to go back up to the if statement condition and invert the whole thing to beign to understand what your else block does.

The Offender

Let’s have a look at some real offensive code. Who knows what it does really… Well, nobody does. Why? Because it’s completely contrived to illustrate my point. And that’s that. Behold the horror!

        private void DoStuff()
        {
            foreach (thing in thisList)
            {
                if (condition1)
                {
                    if (condition2)
                    {
                        DoThis(thing);
                    }
                    else
                    {
                        if (condition3)
                        {
                            continue;
                        }
                        else
                        {
                            if (condition4)
                            {
                                continue;
                            }
                            else
                            {
                                if (condition5)
                                {
                                    if (condition6)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        if (condition7)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            if (condition8)
                                            {
                                                DoThis(thing);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    DoThis(thing);
                }
            }
        }

Pretty filthy, right? In all honesty, anyone who has worked in production code is guaranteed to have seen code that nests much much deeper… veering right off the developer’s window (and some of us code with multiple monitors). It’s a scary world out there, and this example doesn’t even begin to illustrate how bad it can get. I mean, this particular example actually fit on my narrow blog window.

 

A Better Way?

Well, fixing this type of thing is nice and easy:

        private void DoStuff()
        {
            foreach (thing in thisList)
            {
                if (!condition1)
                {
                    DoThis(thing);
                    continue;
                }

                if (condition2)
                {
                    DoThis(thing);
                    continue;
                }
                
                if (condition3 || condition4 || !condition5 || condition6 || condition7)
                {
                    continue;
                }
                
                if (condition8)
                {
                    DoThis(thing);
                }
            }
        }

That’s so much prettier. So what’d I do there? A handful of techniques:

  • Invert logical blocks if they can reduce your nesting. For condition1, I had an if/else block where DoThis(thing) resided in the bottom else block… farrrrr farrrr away from the check itself. I simply inverted this check and moved the else block up. Of course, I then had to put a continue statement there to go back up to the next iteration.
  • For condition2, by simply placing a continue right after the method call in the body, I was able to completely eliminate the else block and reduce nesting by a whole level. This works well with if/else blocks with returns too.
  • Next up was a whole pile of combinations for checking when I’m not going to be calling DoThis(thing). That reduced nesting by a bajillion levels, approximately.
  • The final block there for condition8 was still necessary. Of course, it could have be written to be the inverse check (so, if NOT condition8) with a continue inside the block, followed by DoThis(thing) outside of the if block. To me this would have been a bit overkill.

 

Did You Catch That?

Something extremely important to remember when changing logical flows like this is that the order you check your conditions is EXTREMELY important. Notice how in my refactored version the condition checks are still in the same order that they originally appeared? This is on purpose.
Consider if I move condition8 up to the if statement that tests condition1 and say if NOT condition1, OR condition8. Now this is technically not equivalent to the initial implementation. Why? Because the initial implementation says that for one of the logical paths that call DoThis(thing) the following must be met:
  • condition1 = true
  • conditon2 = false
  • conditon3 = false
  • condition4 = false
  • condition5 = true
  • conditon6 = false
  • condition7 = false
  • condition8 = true

Thus, by combining the condition8 check with the condition1 check, how have I guaranteed all those other conditions?  Additionally, how do I know that skipping those condition checks (i.e. pretend they are method calls) has not altered state elsewhere in the class? This optimization actually may not make the code incorrect in certain situations (because it really depends what those conditions are), but it’s important to note that the checks would not be equivalent to the original. It’s just something to pay attention to, but who knows, you may even find that you can optimize some of those checks away depending on your situation!

 

Summary

Don’t excessively nest your code because it makes me cry at night.

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