Showing posts with label Beginner. Show all posts
Showing posts with label Beginner. Show all posts

Thursday, May 21, 2015

C# Named Arguments

Intro

Whose turn is it to take out the trash? What's the answer to everything? Is Bieber better or is One Direction? Team Jacob or the pasty one? These are some great examples of named arguments.

Wait, what's that? Oh, that's not the kind of named arguments you care to read about? Ok fine. For the record, it's clearly 42, but we'll move on to C# named arguments.



The code sample is in VS 2013 .Net 4.5. Named arguments have been around since VS2010 though so you can follow along with older versions.

Que?

I'm sure you've all seen optional parameters in C# by now. Just in case you haven't, here's an example:

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
        }
    }
}


The method OptionalParams has 3 parameters. The first one is required because it has no default value. 2nd and 3rd parameters are optional; if a caller doesn't specify a value for a parameter, it gets the default value. But hey you already knew this stuff, so let's see what we can do with named arguments.

Here's another sample. This uses the same class and the same 2 methods, but with a slight twist. Starting at line 17, we call the OptionalParams method a couple times, specifying which argument we are populating based on the name of the param rather than using ordering to implicitly specify params. Neat!

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
            //call with named params in order
            OptionalParams(param1: 44, param2: 21);
            //call with named params out of order
            OptionalParams(param3: "blah", param1: 42);
        }
    }
}


Simple eh? You just specify the name of the parameter and the value of the parameter, separated by a colon. I must admit I don't use this trick very much, but it's another tool in yer shed. Use wisely.

Resources

Named and Optional Arguments (C# Programming Guide)

Friday, January 23, 2015

The COUNT Function & NULLs


I'm still a bit under the weather from this cold so I'm going with a short and simple refresher this week.

We all at one time or another have used the SQL COUNT function to look at how many rows of something exists. Some of us have learned the hard way that you have to be careful when using this function. At the very least I hope to give you something to think about.

Let's create a table in our TestDB with this script.

CREATE TABLE [dbo].[tblTestCount]
(
   [id] [int] IDENTITY(1,1) NOT NULL,
   [AllowNulls] [int] NULL,
   [NoNulls] [int] NOT NULL
) ON [PRIMARY]
GO

Now lets put some data into the table.

INSERT INTO tblTestCount ([AllowNulls], [NoNulls])
VALUES (1,1)
,(1,0)
,(null,5)
,(5,4)
,(null,4)
,(3,3)
,(8,10)

Here are the queries we're going to run against the table. Before you run it, write down what you think the results for each query will be. 

SELECT COUNT(1) AS [Query1] FROM [dbo].[tblTestCount]
SELECT COUNT(*) AS [Query2] FROM [dbo].[tblTestCount]
SELECT COUNT([id]) AS [Query3] FROM [dbo].[tblTestCount]
SELECT COUNT([AllowNulls]) AS [Query4] FROM [dbo].[tblTestCount]
SELECT COUNT([NoNulls]) AS [Query5] FROM [dbo].[tblTestCount]
SELECT COUNT(DISTINCT [AllowNulls]) AS [Query6] FROM [dbo].[tblTestCount]
SELECT COUNT(DISTINCT [NoNulls]) AS [Query7] FROM [dbo].[tblTestCount]
SELECT COUNT(DISTINCT *) AS [Query8] FROM [dbo].[tblTestCount]


Did you get them correct? What if anything can you take away from this? Next week, removing duplicate data.

Wednesday, September 24, 2014

JavaScript Pollution

Intro

Everyone knows pollution is bad. It turns rain acidic, makes our roads look terrible, fouls our drinking water, and can cause naming conflicts in our JavaScript code. What? Yeah that's right, our JavaScript code. Write your congressperson I tellz ya! It's a huge problem. But don't fret, there are ways you can mitigate this danger to our very way of life, and I'll show you 2 simple things you can do to lower your global-carbon-JavaScript-namespace footprint.

Que?

Polluting the global namespace is a common term for a common practice in JavaScript. When I create a plain old function in JavaScript such as the following:

function someFunc() {
    window.alert('some text!');
}

someFunc();

I've now committed a cardinal sin, right up there with sloth and eating the last Oreo. I've polluted the global namespace! See how the function someFunc is just floating around in the ether, available to be called from anywhere and without a class or namespace prefix necessary? This is what polluting the global namespace is. This might not seem like a big deal to you. I mean, so what? You're the one writing this code and it's not like you're going to conflict with your own function names right? Well JavaScript is a very open language, and many people these days use multiple 3rd party libraries. Now pretend all these 3rd party libraries are also polluting the global namespace. You'd have naming conflicts between the 3rd party libraries and with your own local code, and that would be quite painful to deal with. How can you, the lowly programmer, prevent your own code from polluting the global namespace? For those of you used to C#, the answer should come naturally: namespaces and classes!

Namespace Example

There are many ways to skin a platypus, and there are many ways to create a namespace in JavaScript. I won't cover all of them, I'll just show you my favorite:

var MyNamespace = MyNamespace || {};

MyNamespace.myInt = 3;


It doesn't get much simpler than that. The first line of code creates our "namespace". It's not really a namespace as JavaScript doesn't support namespaces, but we can useMyNamespace quite similarly to how we us namespaces. We can even nest them if we feel like it. The 2nd line of code just adds a variable named myInt to our namespace. If you want to later created a 2nd javascript file and reuse your namespace, all you have to do is copy that first line to the top of your new file. The magic here is that when we declare MyNamespace, we set it to itself, or if it's undefined, we set it to an empty new object. So if you do this in 1 file or 50 files, you'll either create a new "namespace" object or assign the namespace object to itself, so it works quite easily.

Class Example

Classes take a little more work but they're still not too bad. Here's an example of how to define a class, create an instance of it, and then use it:

//set namespace
var MyNamespace = MyNamespace || {};

//create our class in the namespace
MyNamespace.MyClass = function () {
    this.stringProp = "some string";
    this.intProp = 42;
};

//add the method myFunc to our class
MyNamespace.MyClass.prototype.myFunc = function () {
    window.alert(this.stringProp + "::" + this.intProp);
};

//create a method within the namespace (but not in the class) that creates an instance of the class, sets a property of the object, and calls a method of the object
MyNamespace.doThisStuff = function () {
    var myObj = new MyNamespace.MyClass();
    myObj.stringProp = "yep, still a string";
    myObj.myFunc();
};


The first chunk of code you've seen before; it sets up our namespace.
The 2nd chunk of code defines the class. More accurately, it defines the constructor for our class, within which we also define our class properties stringProp and intProp. We set them to default values too.
The 3rd chunk adds the method myFunc to our class. I won't get into the keyword "prototype", but suffice it to say you should use it when setting methods of your classes so that the method will be instance-level instead of static/class-level.
The 4th chunk of code is a namespace-level method that creates an instance of our class via the new keyword, sets a property value on the instance, and then calls a method on the instance.

All you would have to do now is setup an html file to call your code and you're good to go. You can create as many instances of the class MyClass, which is defined in the namespace MyNamespace as you want to. Have at it!

Summary

I hope you can see the great benefits of using classes and namespaces in JavaScript (well, the strange equivalent of them anyways). Polluting the global namespace can be a tricky problem if you run across it, and preventing the problem is quite easy. Plus it makes your code easier to organize, and in my opinion easier to read. Try it out! It's easy I promise, it just takes a little practice.

What's Next?

  • Read further on objects in JavaScript, and how JavaScript doesn't really support namespaces and classes (we just faked it).
  • Do some more reading on other ways people have come up with to emulate namespaces and classes in JavaScript. You might find one that you like better than what I chose!
  • Learn how to nest your namespaces.
  • Learn how to do inheritance. It's kind of tricky for a language that doesn't really support classes.
  • There is another way to create an instance of a class, Object.create. Read about it.

Resources

Introduction to Object-Oriented JavaScript
My Code

Thursday, September 4, 2014

C# Auto-Implemented Properties

Intro

Ferrari; beautiful sunset; big stack of cash; a hilarious comedy...what do all these things have in common? They're all nearly as cool as c# Auto-Implemented Properties. Yes that's right folks, coding is now cool just like me (ahem). What's an auto-implemented property you ask? Well for starters, thanks for asking. An auto-implemented property is one more thing you can take advantage of to save you some keyboard strokes. Yep that's it folks, less keyboard strokes! (the crowd goes wild). Let's see how auto-implemented properties accomplish such a monumental feat here in the next section.

Example

Here is a very simple example of an auto-implemented property.

    public class Aip
    {
        public string Description { get; set; }
    }


I'm sure you're all used to seeing properties in classes by now. What you might not have seen though is a property that just has "get;" or "set;" within the property declaration, which is an auto-implemented property. Believe it or not, this is a functional class that compiles. You can even get and set the property Description with code like this:

        protected void Page_Load(object sender, EventArgs e)
        {
            var aip = new Aip();
            aip.Description = "hi, i'm tom!";
            Response.Write(aip.Description);
        }


Here we create an object of type Aip, set the description, then read the description. It works just like a normal class with a normal property, only you didn't have to create a (usually private) field behind the property. C# did that for you behind the scenes!

Why?

I already covered this fool! But hey, it's because you can save yourself some time. The above class declaration for Aip is easier than what you would normally do prior to auto-implemented properties:

    public class Aip
    {
        private string mDescription;

        public string Description
        {
            get
            {
                return mDescription;
            }
            set
            {
                mDescription = value;
            }
        }
    }


Yeah it's not a big difference, but it does add up. If you've got a lot of properties to define in an object, give it a whirl! You'll appreciate having a couple extra minutes of your time to do other things.

Limitations

One obvious limitation is that you can't do other things in the getter and setter. They're auto-implemented after all, not manual! So if you need to put any extra logic in your setter or getter, you'll need to implement the property fully yourself.

Limitation 2: Auto-implemented properties must have both a getter and a setter. You can however put the private keyword in front of either the getter or setter to hide them from prying eyes if you really need to.

What's Next

Try it out! I'm sure you've got a project coming up where you can use this.

Resources

Auto-Implemented Properties

Thursday, August 28, 2014

C# Tuple

Intro


What's a Tuple? In the world of .Net, it's a somewhat-generic structure that can hold a number of elements that you define upon declaration/creation. Yeah that's a helpful description, I know. I aim to please! I really can't think of much else to say about these things that will clear up the fog of war, so let's just see a quick sample:

        private Tuple<int, string, int> DoStuffWithNumbers(int num1, int num2)
        {
            int product = num1 * num2;
            string description = "i've done crazy things with numbers";
            int modulus = num1 % num2;
            return new Tuple<int, string, int>(product, description, modulus);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var thing = DoStuffWithNumbers(84, 9);
            Response.Write(thing.Item1 + "::" + thing.Item2 + "::" + thing.Item3);
        }



The above method DoStuffWithNumbers needs to return 3 values. Sure, we could do that with 3 out parameters, but that's a pain! I could also declare a class, maybe call it StuffWithNumbersResult, and give it 3 properties; but yeah, I'm still just as lazy as I was last week so I don't want to create a new class just for that. In comes the Tuple. The method just returns an object (a Tuple) with 3 properties; an int, a string, and another int. The Page_Load method calls DoStuffWithNumbers in the first line, then in the 2nd line it accesses the Tuple via properties Item1, Item2, and Item3. It's not the prettiest way to accomplish things, but it's at least simple. And hey, you still get strongly-typed variables (the method-scope variable "thing" is strongly typed as Tuple<int, string, int>), and you have less coding than you might otherwise.


Why, and Why Not?

The why should be pretty easy to figure out from the above sample. It saves you some coding and by extension a little bit of program complexity. The why not should also be easy to discover. What does thing.Item1 mean? You have to dig into the code to find out, rather than having something more meaningful. For example, if you had declared a StuffWithNumbers class with properties Product, Description, and Modulus, that's a lot more readable than thing.Item1-3. Thus, your code is probably just a wee bit harder to maintain, especially if it's not you doing the maintenance.

Anything Else?

Why of course there's more to it! There's a slightly easier syntax for creating your Tuple which I'm about to show you:

return Tuple.Create(product, description, modulus);

This here line of code can be used in place of the last line from DoStuffWithNumbers() from up above. It's just a slightly simpler way of creating your Tuple without having to use the angle-bracket syntax of generics.

That's about it! Happy Tupling...

What's Next?

Nothing else to say really. Check out the link below though for a few nitpicky details about Tuples. I didn't cover everything, but I covered the fun stuff.

And hey, with great coding power comes great responsibility to future devs who have to maintain your work. Translation: Use Tuples sparingly. If used in excess, they can make your code pretty tough to follow.

Resources
Tuple Class (System)

Thursday, August 21, 2014

Var

Introduction


Sometimes I get lazy. Sometimes I get so lazy, I write a blog post with a 3-letter title. Sometimes I'm so lazy, I don't want to specify the type of a variable in the declaration so I use the keyword var and let the compiler determine the type for me. Yeah, I'm that lazy. Bow down all ye wannabe lazy folk and worship my laziness! The C# keyword var is my friend and my lazy-enabler, so let's discuss it today.

Details

First, a quick sample:

var thingy = new List<int>();

Normally the type of our variable would be List<int>, so you'd see that on both the left and right side of the = sign. However, the var keyword lets us implicitly set the type of the variable based solely on what's on the assignment side of the equation. Some of you might think "i hate stupid dynamic types; compilers and strong types are here for a reason!". Well, I agree with you, and guess what? var variables are in fact strongly typed! You get full intellisense on them in the Visual Studio editor, and the compiler determines the variable type and enforces it at compile type just as it would any other strongly typed variable.

Why?

Why might you want to use var in your own projects? Laziness is the best reason I've got. Let's say that later on you want to change the type of thingy from List<int> to List<long>. If you used var, you only have to change code on the right side of the equation. I know it's a small benefit, but like I said, I'm lazy and I think nearly every good programmer is in some fashion lazy. Less maintenance = more time for the beach! (or for you hardworking folks, more time for new features I guess).

It's also great for saving some typing in foreach loops. Check out this sample:

foreach (var item in bob.Possessions)
{
Console.WriteLine(item.ToString());
}

In this sample, maybe bob.Possessions is a collection of objects of type Possession, but hey it really doesn't matter. The key takeaway here is you don't need to know the exact class name to start up your foreach, and you've saved yourself some typing.


var is indeed for us lazy folks!

Why Not?

var isn't good for everything. I hate to use an incredibly abstract example, but this is about all I can come up with at the moment: Pretend you have an interface called IRepository, used to provide common methods for storing objects "somewhere". You have a class called MongoRepository that implements IRepository and stores your objects in MongoDB, and you have a class called SqlRepository that implements IRepository which stores your objects in SQL Server. Now if you have something like this currently in your code:

IRepository repository = new MongoRepository();


you wouldn't necessarily want to change this to use var. The reason is is because you have an interface that your concrete implementations must realize. Your local variable, being of type IRepository, enforces the contract (interface) but not the type (MongoRepository). If you instead use var, the type of your local variable will be MongoRepository instead of IRepository, which kind of decouples the class from the interface in an abstract sort of way and makes your code less resilient to change.

One more potential drawback: some people might find your code more confusing. Not me personally, but some people. I just find the code more succinct.

Limitations

var variables must be method scope.
var variables must be initialized where declared.

What's Next?

Lookup how to use var with LINQ!
Lookup how to use var with dynamic! (covered in a previous blog post).
var with a using statement is the bee's knees!

Resources

Implicitly Typed Local Variables

Sunday, February 9, 2014

HTML 5 Semantic Element Basics

Grouping Content With HTML 5 and Semantic Elements

As I prepare to learn more about HTML 5, CSS 3, and JavaScript I figured this may be a good time to share what I am learning with some of you in case you had an interest in learning it yourself.  This is very basic information and there may not be anything new to experienced HTML 5 web developers.
 
Many HTML pages used to have their layout defined with tables.  Tables were followed by more elegant CSS solutions.  Semantic Elements can be used to give your content some grouping making the HTML itself easier to interpret.  CSS still allows you to position items in ways HTML 5 cannot but HTML 5 gives you some basic structures to hold your content in without using <div> just to hold grouped content.

Semantic Elements are not new to HTML 5, they are simply elements in HTML that define what is in their content.  Some examples of Semantic Elements that existed in HTML 4 would be <em> used to show emphasis on any content between the opening and closing element, headings such as <h1> used to display varying title sections, and <table> used to display your content in a tabular format many users are familiar with.
 
The Semantic Elements that are new to HTML 5 are:
  • <article>
  • <aside>
  • <details>
  • <figcaption>
  • <figure>
  • <footer>
  • <header>
  • <mark>
  • <nav>
  • <section>
  • <summary>
  • <time>
In this example we'll be creating a basic HTML 5 page using some of the new Semantic Elements.  Some items in our example would normally appear in a master page file so that we could use the same code from page to page but for simplicity we will be stuffing them all into one Default.html page.
 
The first thing we'll want for our page is a header that lets us brand our site and let people know who we are.  As a side note, <header> can be used in a document or a section of a document.  For now we are going to add a <header> element with an <h1> element to hold a title for our website. 

My Sample Website's Header

Now that we are telling everyone who we are, we are ready to give them a space to navigate our site.  Since we don't have a master page we aren't going to put any actual links in this section.  We'll just put some text in it marking it as the navigation section.  We'll use the <nav> element.


Now we'll want to add a section.  We will create a basic <section> with an <aside> element contained within.  When we get more advanced we'll use CSS to push the aside to actually be to the side of our section content.  For now we're keeping it simple.  A section is used to hold related content that will typically have a title to it.  (otherwise why not just use a div)

My Section

<p> This is my section. There are many like it but this one is mine. </p> <p> This is the remainder of my section now that the side note is gone. </p>
After playing briefly with section and aside, we want to briefly visit <article>.  The <article> element looks an awful lot like a <section> element.  Articles are used to display content that can be distributed independent of the website.  Stories that can be displayed via website, RSS feed, forums, blogs, etc.  Other than that, they are pretty much the same as sections.

This Just In: Programmers are Awesome!!!

<p> This is an example of an article element. Looks a lot like a section doesn't it? </p>
Now we want to add a footer to show a copyright to viewers to protect all our hard work.  This is done with a <footer> element.
This is my footer: &copy;ITC Prog Blog 2014
To help us take a look at the placement of all the sections we are adding to this page I am adding an inline style tag (we aren't on CSS yet) to give us a border.  We'll make our body tag on our page have a gray background and all sections within will have a solid border and white background.  I am not including the style tags in the code here to keep the sections cleaner for you to look at.  Here's what our page looks like:  

It is obvious by looking at the page above that semantic elements in HTML 5 don't give you the best layout for your page, but they do help you group your page items logically.  You'll still want CSS to position items on your page properly.  We'll pick up with what we learned next time.

Thursday, November 21, 2013

Unit Testing, Part 1

What is Unit Testing?

Here is the Wikipedia definition of unit testing. To me, unit testing is the use of code whose sole purpose in life is to test other code. Surely you've written a method in the past where you thought to yourself "Man, I feel for the poor tester who gets to test this project. How will they ever run through all 150 scenarios of this method?". I bet you've even written demo programs just to test your code libraries, which is a very similar concept to unit testing. It's code that tests code. Unit tests are generally coded as very simple pass/fail methods where there is no room for interpretation. The test passed or it did not.



Why Should I Do It?

Unit testing can help you as the coder to test your own code, thus ensuring higher quality. It can also be argued that unit testing saves you time, though that seems to be a matter of opinion. From some Google-fu the current prevailing opinion seems to be that in the long-run you will save yourself time by baking unit tests into your projects from the start. It should seem pretty obvious to you now that writing extra code up-front will take extra time up-front, so then the next leap of logic would mean that you save time further down the road, which I have seen myself. Picture a user reporting a bug that they just found out in the field. They have to take the time to call/email support, who researches, sends it over to the group that does the coding, it gets routed to a coder, you have to spend a while tracking it down until you eventually come up with the problem and possibly a solution. Now picture even 25% of those being found through unit tests that are created in the project before its release. Depending on where you look, you can find studies that state bugs found after release cost 15 or 20 times what it costs to find and fix a bug during development, so if you catch even 8% of potential bugs you've saved time in the long-run. Plus, less-buggy software means happier users and a support department which harbors less desire to strangle you in your sleep. One other reason I've found is more of a side effect, but I find that exercising my code through unit tests forces me to design code that has less rigid dependencies and is thus easier to maintain. This is something we'll get into more in a future post.

When Should I Do It?

We are delving more into my own personal opinion here, but I feel that unit testing should be used for *most* code written, whether it be a new development or maintenance/additions. Most importantly, if a bug is found you can usually create a unit test to ensure the bug never returns. This is one of the most helpful uses of unit tests I have found; it acts as a regression test so you and potentially other coders cannot reintroduce a bug into software once it has been fixed. There might be times where unit testing is not appropriate. I hate to say it, but I do believe that if you're in a super time crunch at work and your family doesn't recognize your face anymore, take shortcuts to keep your sanity and ditch the unit tests if you have to, but only if you absolutely have to! Your family has pictures of you after all. You also do not generally want to unit test code that does nothing but hit external resources (flat files, databases, web services, etc), but we'll get into that more in a future post.

I've Heard About Test Driven Development, What's That?
Test Driven Development, or TDD, is a development process whereby the code you write is tested by unit tests prior to the code functioning. It sounds odd but it goes like this (some people show more or fewer steps, but the concept remains):
1) Decide on a specific piece of functionality (chunk of code) you want to write.
2) Write a unit test to call this non-existent piece of code.
3) Compile the unit test; it fails because the code it's calling doesn't yet exist.
4) Create a shell for the piece of functionality; it's usually something as simple as an empty method.
5) Compile+run the unit test; it passes. However, your code doesn't do anything yet, so...
6) Have the unit check that the appropriate resulting condition has occurred.
7) Run the unit test again; it fails because the functional code does nothing yet.
8) Make your code do what it's supposed to do.
9) Run the unit test again; it should pass.
10) Create more unit tests for edge cases, different input, etc etc. Refactor code as necessary to get unit tests created/passed.

There are plenty of people on teh interwebs who will insult your grandmother if you don't zealously enforce TDD in your professional life, but I don't judge (well not about this anyways) so I won't fault you for not using it. Heck I don't use it. I tried it but I find all the bouncing back and forth between the test code and production code to be time-consuming and a little distracting. I work best if I write a small, focused piece of production code first and then test the pants off of it, but do what works best for you. Give TDD a shot and see if you like it. I did, and I don't :)

What's Next?

Well that depends on if you're a teacher's pet or if you like suspense. There's no middle ground here! You can research unit testing further on your own by looking at some of the links below or maybe try some Google-fu, you could try writing some unit tests on your own in your favorite language (it's easy I promise!), or you can wait for next week's blog where I'll show you some introductory unit testing in C#.

Resources

http://en.wikipedia.org/wiki/Unit_testing

http://superwebdeveloper.com/2009/11/25/the-incredible-rate-of-diminishing-returns-of-fixing-software-bugs/

http://en.wikipedia.org/wiki/Test-driven_development

Sunday, November 17, 2013

SOLID Principles

The SOLID principles can lead to less technical debt, easier maintenance, and an ever increasing delivery of software on time.  Bob Martin can be thanked for the SOLID principles.

S - Single Responsibility Principle
O - Open/Close Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle

What IS a principle?  Think of these as rules or concepts that, when followed, produce desirable results in your software.  It's a means to an end, so don't spend all of your time working on SOLID principles while you throw the book of common sense out the window.  There is a balance of each of these principles that, when that balance is met, you achieve software maintenance nirvana.  Be wary...  These principles are more like guidelines, not laws.  You won't be thrown in jail nor will your hair catch fire if it's not followed perfectly, because there are tradeoffs down the road and each of those tradeoffs have their own value.

So let's get started on 'S'.

Single Responsibility Principle  (SRP)

The "Responsibility" is applied to a class.  A class should have only one responsibility.  There are two types of responsibilities: knowing and doing.  As Robert Martin (Uncle Bob) puts it, a class having only one responsibility is like saying that a class should have only one reason for change.

So...  What's a reason for change?  This is where things get a little less obvious in my opinion.  I can argue with myself all day on why even a single method could have more than one reason for change.  I can even argue that if a method has more than one line of code, there's more than one possible "reason" for change.  This isn't the essence of this "guideline", er, I mean "principle".  The essence is in the idea of grouping your methods with other methods that serve a single "role".  Typical roles could be business model related or persistence related or interface related.  A role's interest could change, changing the requirements of the application, but since that role's interest is decoupled from other roles' interests, there's a minimal amount of coding and testing required to implement the requirements for this role's changing interests.

Let's be clear that a role may not be entirely obvious when you "File->New" your project or your new code file, but do remember that we should be refactoring like little boy scouts: Always leave things better than how you found them.

For a brief example, we could take a quick look at ORM's.  The ORM patterns help you separate the responsibility of persisting your data from representing your data (a doing from a knowing).     

Thursday, November 14, 2013

Debugging in Visual Studio, Conditionally

You can use conditional breakpoints to effectively stop your trace based on a predefined condition.  This is extremely useful when you are iterating through large collections of items and you only want to inspect members meeting a specific criteria.  I was going to discuss "Is true" and "Has changed" this week but it appears "Has changed" in Visual Studio 2010 has some unexpected results I want more time to look at before writing about.  So I am doing a shortened post this week.  Sorry. 
 

Simple "Is true" String Comparison Condition

In our first example we'll use a simple string comparison for our breakpoint.  We'll be using a bit of code from Pirate Tips http://www.piratetips.com that I use to display navigation links at the bottom of a page to let you return to the page you previously came from without using your browser's back button.  As you can see I've already added the breakpoint.
Now that I have my breakpoint for some reason I've decided I want to see what's happening in the code when a user is coming back from the page that gives you information about the dreaded Kitten monster from the game Barnacle Wars http://www.barnaclewars.com.  (Don't worry no kittens get killed in the game, they play with balls of yarn)  The title of my page is "Pirate Tips - Beasties: Kitten".
 
  • Right click on your breakpoint.
  • Click Condition on the pop-up menu.
  • Enter your break condition. 
    • Note on more modern versions of Visual Studio Intellisense is available to you as you fill in your condition.
    • When comparing strings I prefer to specify a StringComparison rather than using ToUpper()s, ToLowers()s, etc..
    • In this first example we are using the "Is true" criteria.  There is another criteria called "Has changed".
  • When your condition has been added, click OK.
  • Your breakpoint will now have a + sign in the middle of your red circle.  This means there is a condition on your breakpoint. 
 
  • Now run your debugger as we've discussed in previous posts.
  • Navigate your web page in a manner that will trigger your breakpoint.
  • When you hit your code you will see it highlighted in yellow.
  • In the image below I am indicating with an arrow that in this case I have elected to hover my cursor over PreviousPageTitle to see what the value is.
  • When you're finished simply use your chosen Escape Plan from a previous post to get out of the debugger.
  
 

Tuesday, November 12, 2013

3 Lesser-Known .Net Language Features, in C#

Overview

By the time you're done reading this post you're going to see more question marks than Jim Carrey wore in that God-awful batman movie. Ugh, comedians in tights. Anyways, on to the post. We're going to talk about 3 handy little gems, the conditional operator (?:), nullable types, and the null-coalescing operator (??).

 

Conditional Operator (?:)

I'm a big fan of writing the least amount of code required to get the job done. Partly due to laziness true (I know you were thinking it), but also because the less code that exists now, the less code has to be maintained in the future. Every bit helps. How does the conditional operator work? Let's look at an example:

if (anotherObject.BoolProperty) 
    myObject.StringProperty =  "Bob";
else
    myObject.StringProperty = "Fred";

Here we are setting the value of myObject.StringProperty to either "Bob" or "Fred" depending on the value of anotherObject.BoolProperty, a boolean field. This takes 4 lines of code. We can make this more succinct without losing any meaning or readability through usage of the conditional operator, as follows:

myObject.StringProperty = anotherObject.BoolProperty ? "Bob" : "Fred";

Easy neh? 4 lines of code is now a single line of code.

Nullable Types (?)

Nullable types are pretty cool. In .Net classes you frequently have properties that are basic value types such as integers, booleans, doubles, etc. As you probably know these types cannot be assigned a null value. Well with nullable types you can indeed assign null to these primitives. This might seem like a bit of a niche coding feature, but it really can be quite useful. Take for example an import of data from another system. If your object structure doesn't precisely match the source material, perhaps you want to be able to tell in your destination object structure which fields had a value set from the import process and which did not. If you have a boolean field in your destination object structure, but the import file does not contain this field, can you tell by looking at your object after the fact whether the value was set or not? Normally no you cannot, because the boolean property has only true/false values. However if it's a nullable boolean, a null value could easily be used to represent a lack of information from the import file. OK it's time for an example:

     public class Class1
    {
        public Nullable<int> AnInt { get; set; }
    }

    public class Class2
    {
        public Class2()
        {
            Class1 localObj = new Class1();
            localObj.AnInt = null;
        }
    }

Note the highlighted lines? We can set our property to a null value because it's a nullable type. There's a slightly shorter version of the same property definition as per the below:

public int? AnInt { get; set; }

This code has the exact same meaning as before, it just has fewer characters.

Null-Coalescing Operator (??)

I like to use the null-coalescing operator in conjunction with nullable types. The null-coalescing operator will return the left-hand operator if it is non-null, otherwise it returns the right-hand operator. Let's see another example:

    public class Class1
    {
        public string AString { get; set; }
    }

    public class Class2
    {
        public Class2()
        {
            Class1 localObj = new Class1();
            string localString = null;
            localObj.AString = localString ?? localObj.AString;
        }
    }


The highlighted line is once again the interesting one. Here we are telling the compiler to set localObj.AString to the value localString, unless localString is null (which it is) then localObj.AString gets assigned back to itself, and we did it with a single line of legible code!

Wrapping It Up

I hope you enjoyed this post and are excited to experiment with the above 3 simple yet extremely useful features of the .Net runtime. Drop me a line if you have questions or comments!

Resources



Tuesday, November 5, 2013

Refactoring in Visual Studio, Part 2

Overview

In addition to renaming which we covered in Part 1, Visual Studio has many other refactoring options including extracting a method from an existing block of code, encapsulating a field within a property, extracting an interface from a class, removing parameters, and reordering parameters. Let's see what they do and how to use them.

Extract Method

The "Extract Method" refactor option lets you move a block of code into a new method. Take a look at the below block of code. This code looks like a commonly used block to construct a database command. I would like to move it into a separate method so I can reuse this same logic elsewhere.


To extract a method from this code, you first must select the code as show above. Next right-click within the selected block and select "Refactor-->Extract Method...".


Now you are presented with a dialog where you name your new method, so type in the new name and hit OK.

Your class now has a new method named CreateCommand(), and the prior location serves only to call the new function.


Encapsulate Field

The Encapsulate Field refactoring option takes a field within a class and encapsulates it within a property. This can save you from writing a lot of plumbing when setting up properties with private members. Let's see how it works.

In this class I have a single private field, m_aField. I want to allow other classes to manipulate this value, but in a noble effort to hide the implementation details of this complex chunk of awesome I have decided I want a public property that clients can use. Refactoring to the rescue!


Right-click the field and select "Refactor-->Encapsulate Field...". Visual Studio will select a name for your new field (feel free to change it if you like). Click OK and your code has a brand-spankin-new public property which encapsulates that private field. Yay!


Extract Interface

Now let's take that useful class from the last refactoring option and mangle it further. I have decided that I want multiple classes with the same interface (public properties and methods) as the class RefactoringStuff. The best way to do this is with an interface, and Refactoring can help you here too. Right-click on the class and choose "Refactor-->Extract Interface...".


Visual Studio kindly gives you an opportunity to name your interface and select the properties and methods that will make up the interface definition, so type/select what you like then click the OK button.


Pretty sweet huh? You have a brand new interface named IRefactoringStuff, and the class RefactoringStuff now implements that new interface.

public class RefactoringStuff : ABDebug.IRefactoringStuff
  {
    private string m_aField;
 
    public string AField
    {
      get { return m_aField; }
      set { m_aField = value; }
    }
  }

  interface IRefactoringStuff
  {
    string AField { getset; }
  }

Remove Parameters

Why would you ever want to use a GUI to remove parameters? If your method is called a few times in a few different units, it can be a pain to first manually remove the parameter then go find and change every place that calls the method. So, Visual Studio helps us out once again with Refactor-->Remove Parameters. Take the class below:

  public class RefactoringStuff
  {
    public string AMethod(string param1, string param2)
    {
      return param1 + " !some text in the middle! " + param2;
    }
 
    public void Caller1()
    {
      string local = AMethod("hey""you");
    }
 
    public void Caller2()
    {
      string local = AMethod("hola""senor");
    }
  }

I want to remove param2 from the method AMethod. Right-click in the method and select "Refactor-->Remove Parameters". Select the parameter you want to remove and click the Remove button. Click OK when done.


You are presented with another dialog where you can preview the changes that Visual Studio is going to make. Review it's plan and click OK when ready.


Boom! code modded. But hey wait just a minute here fella, my code doesn't compile! Yeah well nobody's perfect, including Visual Studio. You'll notice in the code below that param2 is still referenced in AMethod. Just get rid of it manually and move along.

  public class RefactoringStuff
  {
    public string AMethod(string param1)
    {
      return param1 + " !some text in the middle! " + param2;
    }
 
    public void Caller1()
    {
      string local = AMethod("hey");
    }
 
    public void Caller2()
    {
      string local = AMethod("hola");
    }
  }

Reorder Parameters

The last option we'll cover is reordering parameters. I won't get into much in the way of screenshots as you've probably figured out the process by now and are just about tired of reading, so let's just take a quick look at some code. Here we're back to the class RefactoringStuff. I want to switch the order of param1 and param2 in the method AMethod.

  public class RefactoringStuff
  {
    public string AMethod(string param1, string param2)
    {
      return param1 + " !some text in the middle! " + param2;
    }
 
    public void Caller1()
    {
      string local = AMethod("hey""you");
    }
 
    public void Caller2()
    {
      string local = AMethod("hola""senor");
    }
  }

Right-click within the method AMethod and select "Refactor-->Reorder Parameters...". Use the dialog to reorder parameters as you desire, click OK, the preview window then comes up, review your changes, click Apply. The parameters in AMethod have been reordered and all calls to AMethod have had their parameters switch around as well.


    public string AMethod(string param2, string param1)
    {
      return param1 + " !some text in the middle! " + param2;
    }
 
    public void Caller1()
    {
      string local = AMethod("you""hey");
    }
 
    public void Caller2()
    {
      string local = AMethod("senor""hola");
    }
  }

Thanks for your time again folks, and if you enjoyed this post be sure give us a big happy +1 in google, share us on facebook and twitter, subscribe to the blog, tell your neighbors and your neighbor's dog. Comments are encouraged!

Sunday, November 3, 2013

Debugging in Visual Studio, Breakpoints

Breakpoints Basics

Last time we talked about the basics of running the debugger in Visual Studio.  Today let's talk about breakpoints.  There are several ways to add a breakpoint to your code.  A note about colors in this post: I will describe items in the color they appear in my IDE, it's possible you have your colors set differently than mine.  Either way, the colors mentioned in the writings will help guide you through the pictures included.

When Can I Add a Breakpoint?

  • A breakpoint can be added before you begin to run your code. 
  • A breakpoint can also be added during runtime by placing a breakpoint anywhere in the code.  If you expect to hit a breakpoint you added during runtime you should probably place it in a section you haven't yet passed in the code or at least in a section there is a way for you to return to.
  • A type of breakpoint can be added dynamically before running the debugger and without actually adding a breakpoint.  We'll call this Run To Cursor and cover this later in the post.

Where Can I Place Breakpoints?

You can add a breakpoint just about anywhere in your code.  Some places you cannot add breakpoints are listed below:
  • Whitespace.
  • Comments.
  • Decision structure with no actual code.  (i.e. if and else if are ok, the fall-through else will not be a place you can add a breakpoint)  Breakpoints can be added in a code block contained in the fall-through else.
  • Try and Finally cannot have a breakpoint added.  You can however add one to your Catch.  Breakpoints can be added in a code block contained in your Try/Finally.
  • Case and Default in a switch cannot have a breakpoint.  Breakpoints can be added in a block of code contained in your Case or Default.

Adding Your Breakpoint

  • One way to add a breakpoint is to click in the gray vertical space to the left of your code.  Your breakpoint will appear where you've clicked. 
 
  • Another way to add a breakpoint is to put your cursor where you want your breakpoint, click Debug then in the dropdown menu click Toggle Breakpoint.
 
  • If you are into keyboard shortcuts you may also add a breakpoint by putting your cursor on the line you wish to see a breakpoint and pressing the F9 key.
  • With your cursor on the line you'd like to add your breakpoint to you may also right click on your line of code, hover over Breakpoint on the pop-up menu, then click Insert Breakpoint on the pop-up menu that comes up after that. 

     
No matter which method you use to add your breakpoint, when you have an active breakpoint you will see a solid red circle in the gray vertical bar and the line of code your breakpoint is in will be highlighted in red like below:
 

Removing Your Breakpoint

Just like adding a breakpoint, you have several options to remove a breakpoint.  You can start by reversing the steps you've already been shown:
  • Click the solid red circle in the gray vertical bar to the side of your code.  Your breakpoint will go away.
  • With your cursor on the line of code for the breakpoint you want to get rid of, click Debug then in the dropdown menu click Toggle Breakpoint.
  • With your cursor on the line of code for the breakpoint you want to get rid of, press the F9 key.
  • With your cursor on the line of code for the breakpoint you want to get rid of right click in the line of code and hover over Breakpoint in the pop-up menu that displays, then click Delete Breakpoint on the menu that pops up after that.
 
There are also a couple of other ways to remove your breakpoints:
  • You can right click your breakpoint, a menu will pop-up click Delete Breakpoint.  There are other options available we will cover many of them in future posts. 
 
  • You can also click Debug then in the dropdown menu click Delete All Breakpoints.  This method will remove any other breakpoints you have added to this entire solution.
You will receive a confirmation message, click Yes if you truly wish to delete all breakpoints.
 
  • For those of you keyboard shortcut junkies, you can fire off Delete All Breakpoints by pressing Ctrl+Shift+F9 at the same time.

Run To Cursor

One last option to break on a line of code doesn't require breakpoints.  With your cursor on the line of code you wish to break on, right click and in the pop-up menu that displays click Run To Cursor.  Your code will launch.
To escape this type of debugging, you can close your browser if you are debugging a web application, close your executable if you are debugging a Windows application, or regardless of which type you are debugging you can click the Blue Stop Button on the toolbar menu.
 
 

Friday, November 1, 2013

My Favorite Visual Studio Keyboard Shortcuts

I hate using my mouse.  I'm always looking for ways to cut out the travel time between my keyboard and mouse.  The repetition is hard on my arthritic wrist and it takes a significant amount of time.  Vim, in my eyes, is the holy grail of keyboard shortcut mastery.  There are games to help us on the outside get a grip on the Vim user interface.  Yes, there is a Vim plug-in for Visual Studio for the hardcore among us.  But...  I'm not there yet, so I thought I'd share the ones I use regularly, and where I go to learn new ones.
  1. Editor Related
    1. CTRL + S = Save
    2. CTRL + SHIFT + S = Save all
    3. CTRL + C = Copy
    4. CTRL + X = Cut
    5. CTRL + V = Paste
    6. CTRL + K + CTRL + D = Format code (puts nice spaces and indentations where you like them)
    7. ALT + SHIFT + T = Swaps the current line with the line below it
    8. CTRL + SHIFT + B = Build baby build!
    9. CTRL + D +  T = Debug unit test that is in context
    10. CTRL + R + T = Run unit test that is in context
    11. CTRL + K + CTRL + C = Comment out current line or selection of code
    12. CTRL + K + CTRL + U = Uncomment current line or selection of cote
    13. CTRL + . (that's a period) = Used to bring up context menu when you see the little underline or context menu icon show up after a code change. Mostly used during refactorings like changing a variable name or extracting a method from selected code.
    14. Context Menu Key (this is the key on my keyboard between right ALT and right CTRL) = Primarily used to access refactoring menus to create new functions or new variables.
    15. CTRL + F = Find
    16. CTRL + H = Replace
    17. CTRL + SHIFT + F = Find many (gives me a list of all instances)
    18. F3 = Move to next instance of matching text for a find text request
    19. SHIFT + F3 = Move to the previous instance of matching text for a find text request
    20. F9 = Toggle breakpoint
    21. F12 = Go to definition of the variable, method, or class
    22. CTRL + TAB = Switch between open files much like ALT + TAB and WINDOWS + TAB does in Windows.
    23. CTRL + F4 = Close currently focused code file
    24. CTRL + Spacebar = Give me intellisense and give it to me NOW!
  2. Debugger Related
    1. F5 = Run
    2. F9 = Toggle breakpoint
    3. F10 = Run current line of code only
    4. F11 = Step into function on current line of code
    5. SHIFT + F11 = Finish running current function and break in calling function

And one of my favorite quotes on shortcuts from the movie Road Trip:

It's supposed to be a challenge, that's why they call it a shortcut. If it was easy it would just be the way.

I'm sure I'm missing a few, so please add others that you use in the comments.