I am happy to announce that I've been commissioned to produce a course for Pluralsight (http://www.pluralsight.com).
If you're not familiar with Pluralsight, be sure to check it out. They offer high-quality video training by experts in the field. There's a 10-day free trial so you can get a taste for what it's like. And they have a number of free courses, including "Teaching Kids Programming with C#" by Lynn Langit and Llewellyn Falco.
My first experience with Pluralsight was when I needed to get up to speed on ASP.NET MVC (way back in the version 1 days). Their course gave me exactly what I was looking for: I came away with a good understanding of the technology and its capabilities. It turned out that my particular scenario fit the technology perfectly, and I went on to create a mobile-friendly web application with ASP.NET MVC.
That was several years ago. Since then, the catalog has been constantly expanding. There's lots of good stuff to check out.
And don't worry, I'll be sure to announce when my first course is available.
Happy Coding!
Friday, May 17, 2013
Wednesday, May 8, 2013
Screencast: C# Properties
A couple of weeks ago, I talked a bit about properties: Explained: Properties in .NET. Since this sample has a lot of clicking and navigating, it's a good candidate for a screencast.
So, if you'd like to see how to navigate around in ILDASM (and also see Visual Studio code snippets in action), you can check out the video posted on YouTube: http://www.youtube.com/watch?v=v_BXErPuksA.
Happy Coding!
So, if you'd like to see how to navigate around in ILDASM (and also see Visual Studio code snippets in action), you can check out the video posted on YouTube: http://www.youtube.com/watch?v=v_BXErPuksA.
Happy Coding!
Labels:
Automatic Properties,
Properties,
Video
Monday, May 6, 2013
Prism for Windows Runtime (formerly Kona)
Kona, the guidance package from Microsoft Patterns & Practices for writing Windows App Store LOB apps (previously mentioned here: Application Guidance Update: Kona and Prism), has a new name: Prism for Windows Runtime.
Here are some relevant links.
Download from CodePlex:
http://prismwindowsruntime.codeplex.com/
A "Getting Started" article from Brian Noyes:
http://www.silverlightshow.net/items/Windows-Store-LOB-Apps-with-Kona-Getting-Started.aspx
As a reminder, Prism for Windows Runtime and Prism 4 (for WPF and Silverlight) are different packages with different capabilities. As mentioned in previous article, this is primarily due to the differences in the underlying platforms and what makes sense in each environment.
If you build Line of Business applications, and you're moving into the Windows App Store world, it's worth checking out.
Happy Coding!
Here are some relevant links.
Download from CodePlex:
http://prismwindowsruntime.codeplex.com/
A "Getting Started" article from Brian Noyes:
http://www.silverlightshow.net/items/Windows-Store-LOB-Apps-with-Kona-Getting-Started.aspx
As a reminder, Prism for Windows Runtime and Prism 4 (for WPF and Silverlight) are different packages with different capabilities. As mentioned in previous article, this is primarily due to the differences in the underlying platforms and what makes sense in each environment.
If you build Line of Business applications, and you're moving into the Windows App Store world, it's worth checking out.
Happy Coding!
Sunday, May 5, 2013
Book Review: Don't Make Me Think
I'm still powering through my Reading List for this year. I recently finished Don't Make Me Think: A Common Sense Approach to Web Usability by Steve Krug (Amazon Link). The second edition of this book (the one I read) was published in 2006 and is in its 13th printing, so it's been around a while. But it has stood up to the test of time.
Krug is a usability consultant -- his job is to set up user testing of web sites and report the findings. This book helps you do the bulk of this work yourself. As Krug would say, it isn't a replacement for a usability professional, but most of us won't spend the money on one. This book shows that you don't need to be a professional to get useful results out of user testing.
This is a purposefully short book (under 200 pages with lots of diagrams and pictures). So, I won't go into too many details. But I'll point out one or two things that I found particularly useful.
Usable Web Sites
Don't Make Me Think focuses on how to create usable web sites (note: web sites, not web applications). With that said, you can get a lot just from the chapter titles. Here are the first 7 chapters:
Krug's Laws of Usability
In addition to the chapter titles, we get Krug's Laws:
Krug bases these laws on how people actually use the web. People don't stop to read every word on a page. They usually go to a site for a specific purpose (such as to find the address of a store location). They don't care about the "fluff". They don't really care about the welcome message. They are scanning the home page looking for a link that looks like it's "close enough."
If we keep this in mind, the laws make perfect sense. We want information on our web site to be clearly available and for links to be as obvious as possible.
Usability as Common Courtesy
Chapter 10 talks about the Reservoir of Good Will. This reservoir can be diminished when the user has trouble finding information, or it can be refilled by easily giving him just what he is looking for. If the reservoir is depleted, then the user simply abandons the site.
I never thought about usability in this fashion before. But I've noticed in the last week or so that this is exactly how I use web sites. For example, I was looking for the hours of the local e-waste drop off location (I knew where the location was, just not when they were open).
I did a couple of web searches but didn't find what I was looking for. Then I went to my municipality's web site and still had a bit of difficulty finding what I was looking for. I finally stumbled across the listing of the drop-off locations, but I didn't see any hours listed. I ended up loading up the car and heading over there only to see a "Closed Mondays" sign on the gate (and guess what day it was?). I went back to the site later and found the hours buried in a block of text (9 am - 3 pm Tuesday through Saturday).
Krug gives a list of things that can diminish the reservoir, including hiding information that I really want or asking for information that you don't really need (do you really need my phone number to sign me up for an email newsletter?).
Conversely, there are a number of things that help to refill the reservoir such as tell me what I want to know and save me steps wherever you can.
Wrap Up
I would recommend Don't Make Me Think to anyone with a web site. It will make you stop and think about how people actually use your site. The examples focus on e-commerce sites (simply for consistency), but the principles apply to whatever web site you may have. Keep the user in mind, and don't make him think.
Happy Coding!
Krug is a usability consultant -- his job is to set up user testing of web sites and report the findings. This book helps you do the bulk of this work yourself. As Krug would say, it isn't a replacement for a usability professional, but most of us won't spend the money on one. This book shows that you don't need to be a professional to get useful results out of user testing.
This is a purposefully short book (under 200 pages with lots of diagrams and pictures). So, I won't go into too many details. But I'll point out one or two things that I found particularly useful.
Usable Web Sites
Don't Make Me Think focuses on how to create usable web sites (note: web sites, not web applications). With that said, you can get a lot just from the chapter titles. Here are the first 7 chapters:
- Don't make me think! - Krug's First Law of Usability
- How we really use the Web - Scanning, satisficing, and mudding through
- Billboard Design 101 - Designing pages for scanning, not reading
- Animal, vegetable, or mineral? - Why users like mindless choices
- Omit
needlesswords - The art of not writing for the Web - Street signs and Breadcrumbs
- The first step in recovery is admitting that the Home Page is beyond your control
Krug's Laws of Usability
In addition to the chapter titles, we get Krug's Laws:
- Don't make me think!
- It doesn't matter how many times I have to click, as long as each click is a mindless, unambiguous choice.
- Get rid of half of the words on each page, then get rid of half of what's left.
Krug bases these laws on how people actually use the web. People don't stop to read every word on a page. They usually go to a site for a specific purpose (such as to find the address of a store location). They don't care about the "fluff". They don't really care about the welcome message. They are scanning the home page looking for a link that looks like it's "close enough."
If we keep this in mind, the laws make perfect sense. We want information on our web site to be clearly available and for links to be as obvious as possible.
Usability as Common Courtesy
Chapter 10 talks about the Reservoir of Good Will. This reservoir can be diminished when the user has trouble finding information, or it can be refilled by easily giving him just what he is looking for. If the reservoir is depleted, then the user simply abandons the site.
I never thought about usability in this fashion before. But I've noticed in the last week or so that this is exactly how I use web sites. For example, I was looking for the hours of the local e-waste drop off location (I knew where the location was, just not when they were open).
I did a couple of web searches but didn't find what I was looking for. Then I went to my municipality's web site and still had a bit of difficulty finding what I was looking for. I finally stumbled across the listing of the drop-off locations, but I didn't see any hours listed. I ended up loading up the car and heading over there only to see a "Closed Mondays" sign on the gate (and guess what day it was?). I went back to the site later and found the hours buried in a block of text (9 am - 3 pm Tuesday through Saturday).
Krug gives a list of things that can diminish the reservoir, including hiding information that I really want or asking for information that you don't really need (do you really need my phone number to sign me up for an email newsletter?).
Conversely, there are a number of things that help to refill the reservoir such as tell me what I want to know and save me steps wherever you can.
Wrap Up
I would recommend Don't Make Me Think to anyone with a web site. It will make you stop and think about how people actually use your site. The examples focus on e-commerce sites (simply for consistency), but the principles apply to whatever web site you may have. Keep the user in mind, and don't make him think.
Happy Coding!
Labels:
Book Review,
Design
Thursday, May 2, 2013
May 2013 Speaking Engagements
I've got two speaking engagements currently scheduled for May. If you're in the area, be sure to stop by.
Wednesday, May 8, 2013
vNext OC
http://www.meetup.com/vNext-OrangeCounty/
Newport Beach, CA
Topic: IEnumerable, ISaveable, IDontGetIt: Understanding .NET Interfaces
When we use abstraction judiciously, we end up with extensible, maintainable, and testable code. And interfaces are an important way that we can add abstraction to our code. As with most of my presentations, we focus on applying these concepts in our code, both by using existing interfaces from the .NET framework and by creating our own interfaces. Along the way, we find that interfaces aren't that complicated and give us some tangible benefits.
Tuesday, May 28, 2013
San Diego .NET User Group
http://www.sandiegodotnet.com/
San Diego, CA
Topic: Dependency Injection: A Practical Introduction
I have a great time presenting on Dependency Injection -- mostly because I can see the light bulbs go on as we go through the samples. DI seems like an advanced topic, but the concepts are pretty straight forward. There are tons of techniques, patterns, and tools. This session covers the basics and will give you a desire to learn more.
Happy Coding!
Wednesday, May 8, 2013
vNext OC
http://www.meetup.com/vNext-OrangeCounty/
Newport Beach, CA
Topic: IEnumerable, ISaveable, IDontGetIt: Understanding .NET Interfaces
When we use abstraction judiciously, we end up with extensible, maintainable, and testable code. And interfaces are an important way that we can add abstraction to our code. As with most of my presentations, we focus on applying these concepts in our code, both by using existing interfaces from the .NET framework and by creating our own interfaces. Along the way, we find that interfaces aren't that complicated and give us some tangible benefits.
Tuesday, May 28, 2013
San Diego .NET User Group
http://www.sandiegodotnet.com/
San Diego, CA
Topic: Dependency Injection: A Practical Introduction
I have a great time presenting on Dependency Injection -- mostly because I can see the light bulbs go on as we go through the samples. DI seems like an advanced topic, but the concepts are pretty straight forward. There are tons of techniques, patterns, and tools. This session covers the basics and will give you a desire to learn more.
Happy Coding!
Labels:
Event
Tuesday, April 30, 2013
Explained: Properties in .NET
Properties in .NET seem a bit curious when you're new to the framework. They look like data, but that's not quite how they behave. Things can get even more confusing when using the automatic property syntax (which is awesome if you know what it's actually doing). So, let's take a bit of a deeper dive to see exactly what's going on in a .NET property.
Note: A video version of this article is also available on YouTube: JeremyBytes - C# Properties.
Property with a Backing Field
We'll create a simple "Person" class to explore properties. Here's a typical property that has a backing field:
First, we have a private backing field ("firstName"). Then we have our public property ("FirstName") that has both a getter and a setter to access the backing field. The getter returns the value of the backing field, and the setter sets the value of the backing field.
Note: You can easily create a property with a backing field using the "propfull" snippet in Visual Studio. To do this, go to a blank line and type "propfull". IntelliSense will show this as "Code snippet for property and backing field". When you press Tab, it stubs out the code for you. Then you get 3 highlighted items. The first ("int" by default) is the type. Just update this with the type you want ("string" in our case), and press Tab. This will take you to the name of the backing field. Update the name and press Tab again to go to the name of the property. When you're done, just hit Enter. Snippets are awesome for this kind of stuff.
This syntax looks a bit strange at first, but it's simply a shorthand way encapsulating a field. This will become a bit more clear when we compare it to another language.
Get / Set Methods
Java has a different paradigm for this type of encapsulation. The data is still hidden in a private field, but a pair of methods (get / set) are used to access this data. Here's a phone number "property" that uses this type of syntax:
(Note: this is still C# code, but it's written in the Java property style -- I've also used the "curly braces on the same line" format, but we already know that this doesn't really matter). This code makes things a bit more clear. We have encapsulated our data with a pair of accessor methods.
By encapsulation, I mean that we have hidden our data ("phoneNumber") and provided specific methods ("get_PhoneNumber" and "set_PhoneNumber") that we can use to interact with the data from the outside world . We could easily create a read-only property by simply omitting the "set" method. Our data is safely hidden behind a public interface, and we can be confident that it cannot be modified without our class knowing about it.
.NET Properties are Methods
It turns out that properties in .NET also use get and set methods to control access to the data. The difference is that these methods are hidden from our view. Let's look at the IL that is generated by the code we've seen so far.
We'll use ildasm.exe to look inside our assembly. If you want to see how to add IL DASM to your Visual Studio tools, take a look at this article: Book Review: Professional .NET Framework 2.0 (yes, the instructions are part of a book review I did).
Here's the overview of our class in IL DASM:
There are a couple of interesting things here. First, notice our backing fields (with the teal diamonds). Both "firstName" and "phoneNumber" are private string fields. This is exactly what we would expect.
In our methods (the purple squares), we see the "get_PhoneNumber" and "set_PhoneNumber" methods that we created ourselves. But we also see "get_FirstName" and "set_FirstName". These methods were generated by the compiler from our property.
The last item (the red triangle) is our "FirstName" property. Here's what it does:
This says that when someone tries to "get" the property, the method "get_FirstName" should be called. When someone tries to "set" the property, then then method "set_FirstName" should be called. This is how our property gets wired up to those compiler-generated methods.
If we compare the getters for our two properties, we see that the look almost exactly the same:
When we look at the method body, we see "ldarg.0" (load argument) -- this is at the beginning of every instance method. It pushes "this" (which is argument 0) onto the stack so that it can be used in the method. Next, we have "ldfld" (load field) -- this pushes the value of the specified field onto the stack. We can see that the each method pushes "firstName" or "phoneNumber" as appropriate.
Finally, we have the "ret" (return) -- this returns the value on the top of the stack, which happens to be the field that we just pushed.
Note: This sample is built as "Release". If you build as "Debug", then you may see some "nop" (no operation) instructions. There are placeholders so that you can set breakpoints on the curly braces in the source code.
If we look at the method declaration (at the top), we see that these two methods are *almost* identical. The difference is that "get_FirstName" has the "specialname" attribute specified. This means that "get_FirstName" is a special method that cannot be called by user code. If you try to put "person.get_FirstName()" in your code, you'll just get a compiler error. We aren't allowed to access this method directly.
Other than that, we can see that there's no real difference between our manual getter (for the "phoneNumber" field) and the compiler-generated getter (for the "FirstName" property).
Automatic Properties
In C# 3.0 (.NET 3.5), we got some new syntax for creating properties: automatic properties. Here's a sample:
The automatic property syntax is simply a shortcut. If we don't need to do anything special in the getter or setter (more on this below), then this shorthand saves us from having to type out the standard implementation of the getter and setter (it also saves us from having to create a separate backing field).
Note: Automatic properties can be created with the "prop" snippet. This only has 2 editable items: the type and the property name. This snippet doesn't save nearly as much typing as "propfull", but it can still be useful.
So, let's compare our full property ("FirstName") to the automatic property ("LastName") to see what the compiler builds for us. First, an overview:
We now have a new field: "<LastName>k__BackingField". So, even though we don't create a backing field in our code, the compiler generates one for us. It uses the strange name so that there won't be any potential naming conflicts with non-generated code.
Here's the IL for the "firstName" field and the "<LastName>k__BackingField":
There's no surprises for the "firstName". It just shows it as a private string field. Notice that the first line of the LastName backing field looks similar: it just shows a private string field.
The next line is an attribute noting that this field was generated by the compiler (there's actually a bit more code that has been truncated from this screenshot).
Finally, let's compare the getters for these two properties:
Here we see that the getters are exactly the same (except for the CompilerGeneratedAttribute). This shows us that if we use automatic properties, we get (almost) exactly the same code as if we use a property with a backing field.
One thing to note about automatic property syntax is that we must have both the "get;" and the "set;". If you want to make a read-only property, this is easy to get around: just make the setter private. For example:
This has the effect of making the property read-only. It cannot be set from outside of the class (but we can still set it internally).
Why Don't We Always Use Automatic Properties?
So, since we see that the property with the backing field and the automatic property generate the same IL, why would we ever want to use a property with a manual backing field?
There are a couple of answers to this. First, sometimes we want to do some more work in the getter (other than just retrieving the value of the backing field). For example, we may want the getter to supply a default value for a property if the backing field is null. We may also want to use Property Injection (see: Dependency Injection: A Practical Introduction).
More frequently, we want to do more work in the setter. We can put validation code in the setter that would reject an invalid value. Or we can put security code in the setter that would only update the backing field if you have proper authorization. Or we may want to fire an event to notify other objects that the value has changed.
This last scenario is very common in the XAML and WinForms databinding world. "INotifyPropertyChanged" is an interface that specifies an event that can be fired when data is changed programmatically. This notifies the UI that something is different and it needs to update the values that are displayed in the controls. Here's an example of this type of setter:
Here we see that the setter has a bit more code in it. First, we check to see if the incoming value already matches what's in the backing field. If the data is unchanged, we "return" -- short-circuiting the rest of the setter. Otherwise, we set the backing field and then raise the notification event.
Optimization Note: the "if" statement is not required; it just saves the firing of the notification event. But conditionals also have a little bit of overhead, so you may want to re-evaluate whether the conditional is advisable based on your particular application.
So, we see that there are a few reasons why we may want to supply our own backing field and get/set implementation.
Wrap Up
The .NET property syntax is a bit odd when you first see it, especially if you are coming from a language that doesn't have this type of property implementation. As we've seen, properties are just sets of methods that help us encapsulate our data.
Whether we create our own backing fields or use automatic properties depends on how we're using them. For example, a DTO (Data Transfer Object) is just used to move data around. For these, we can use automatic properties. In contrast, if we have a View Model with properties that need to be databound, we'll probably want to have "full" properties so that we can fire notification events when the values are changed in the setters.
Properties are everywhere, and they are incredibly useful. Hopefully, this has given you a better insight into what's going on "under the covers."
Happy Coding!
Note: A video version of this article is also available on YouTube: JeremyBytes - C# Properties.
Property with a Backing Field
We'll create a simple "Person" class to explore properties. Here's a typical property that has a backing field:
First, we have a private backing field ("firstName"). Then we have our public property ("FirstName") that has both a getter and a setter to access the backing field. The getter returns the value of the backing field, and the setter sets the value of the backing field.
Note: You can easily create a property with a backing field using the "propfull" snippet in Visual Studio. To do this, go to a blank line and type "propfull". IntelliSense will show this as "Code snippet for property and backing field". When you press Tab, it stubs out the code for you. Then you get 3 highlighted items. The first ("int" by default) is the type. Just update this with the type you want ("string" in our case), and press Tab. This will take you to the name of the backing field. Update the name and press Tab again to go to the name of the property. When you're done, just hit Enter. Snippets are awesome for this kind of stuff.
This syntax looks a bit strange at first, but it's simply a shorthand way encapsulating a field. This will become a bit more clear when we compare it to another language.
Get / Set Methods
Java has a different paradigm for this type of encapsulation. The data is still hidden in a private field, but a pair of methods (get / set) are used to access this data. Here's a phone number "property" that uses this type of syntax:
(Note: this is still C# code, but it's written in the Java property style -- I've also used the "curly braces on the same line" format, but we already know that this doesn't really matter). This code makes things a bit more clear. We have encapsulated our data with a pair of accessor methods.
By encapsulation, I mean that we have hidden our data ("phoneNumber") and provided specific methods ("get_PhoneNumber" and "set_PhoneNumber") that we can use to interact with the data from the outside world . We could easily create a read-only property by simply omitting the "set" method. Our data is safely hidden behind a public interface, and we can be confident that it cannot be modified without our class knowing about it.
.NET Properties are Methods
It turns out that properties in .NET also use get and set methods to control access to the data. The difference is that these methods are hidden from our view. Let's look at the IL that is generated by the code we've seen so far.
We'll use ildasm.exe to look inside our assembly. If you want to see how to add IL DASM to your Visual Studio tools, take a look at this article: Book Review: Professional .NET Framework 2.0 (yes, the instructions are part of a book review I did).
Here's the overview of our class in IL DASM:
There are a couple of interesting things here. First, notice our backing fields (with the teal diamonds). Both "firstName" and "phoneNumber" are private string fields. This is exactly what we would expect.
In our methods (the purple squares), we see the "get_PhoneNumber" and "set_PhoneNumber" methods that we created ourselves. But we also see "get_FirstName" and "set_FirstName". These methods were generated by the compiler from our property.
The last item (the red triangle) is our "FirstName" property. Here's what it does:
This says that when someone tries to "get" the property, the method "get_FirstName" should be called. When someone tries to "set" the property, then then method "set_FirstName" should be called. This is how our property gets wired up to those compiler-generated methods.
If we compare the getters for our two properties, we see that the look almost exactly the same:
When we look at the method body, we see "ldarg.0" (load argument) -- this is at the beginning of every instance method. It pushes "this" (which is argument 0) onto the stack so that it can be used in the method. Next, we have "ldfld" (load field) -- this pushes the value of the specified field onto the stack. We can see that the each method pushes "firstName" or "phoneNumber" as appropriate.
Finally, we have the "ret" (return) -- this returns the value on the top of the stack, which happens to be the field that we just pushed.
Note: This sample is built as "Release". If you build as "Debug", then you may see some "nop" (no operation) instructions. There are placeholders so that you can set breakpoints on the curly braces in the source code.
If we look at the method declaration (at the top), we see that these two methods are *almost* identical. The difference is that "get_FirstName" has the "specialname" attribute specified. This means that "get_FirstName" is a special method that cannot be called by user code. If you try to put "person.get_FirstName()" in your code, you'll just get a compiler error. We aren't allowed to access this method directly.
Other than that, we can see that there's no real difference between our manual getter (for the "phoneNumber" field) and the compiler-generated getter (for the "FirstName" property).
Automatic Properties
In C# 3.0 (.NET 3.5), we got some new syntax for creating properties: automatic properties. Here's a sample:
The automatic property syntax is simply a shortcut. If we don't need to do anything special in the getter or setter (more on this below), then this shorthand saves us from having to type out the standard implementation of the getter and setter (it also saves us from having to create a separate backing field).
Note: Automatic properties can be created with the "prop" snippet. This only has 2 editable items: the type and the property name. This snippet doesn't save nearly as much typing as "propfull", but it can still be useful.
So, let's compare our full property ("FirstName") to the automatic property ("LastName") to see what the compiler builds for us. First, an overview:
We now have a new field: "<LastName>k__BackingField". So, even though we don't create a backing field in our code, the compiler generates one for us. It uses the strange name so that there won't be any potential naming conflicts with non-generated code.
Here's the IL for the "firstName" field and the "<LastName>k__BackingField":
There's no surprises for the "firstName". It just shows it as a private string field. Notice that the first line of the LastName backing field looks similar: it just shows a private string field.
The next line is an attribute noting that this field was generated by the compiler (there's actually a bit more code that has been truncated from this screenshot).
Finally, let's compare the getters for these two properties:
Here we see that the getters are exactly the same (except for the CompilerGeneratedAttribute). This shows us that if we use automatic properties, we get (almost) exactly the same code as if we use a property with a backing field.
One thing to note about automatic property syntax is that we must have both the "get;" and the "set;". If you want to make a read-only property, this is easy to get around: just make the setter private. For example:
This has the effect of making the property read-only. It cannot be set from outside of the class (but we can still set it internally).
Why Don't We Always Use Automatic Properties?
So, since we see that the property with the backing field and the automatic property generate the same IL, why would we ever want to use a property with a manual backing field?
There are a couple of answers to this. First, sometimes we want to do some more work in the getter (other than just retrieving the value of the backing field). For example, we may want the getter to supply a default value for a property if the backing field is null. We may also want to use Property Injection (see: Dependency Injection: A Practical Introduction).
More frequently, we want to do more work in the setter. We can put validation code in the setter that would reject an invalid value. Or we can put security code in the setter that would only update the backing field if you have proper authorization. Or we may want to fire an event to notify other objects that the value has changed.
This last scenario is very common in the XAML and WinForms databinding world. "INotifyPropertyChanged" is an interface that specifies an event that can be fired when data is changed programmatically. This notifies the UI that something is different and it needs to update the values that are displayed in the controls. Here's an example of this type of setter:
Here we see that the setter has a bit more code in it. First, we check to see if the incoming value already matches what's in the backing field. If the data is unchanged, we "return" -- short-circuiting the rest of the setter. Otherwise, we set the backing field and then raise the notification event.
Optimization Note: the "if" statement is not required; it just saves the firing of the notification event. But conditionals also have a little bit of overhead, so you may want to re-evaluate whether the conditional is advisable based on your particular application.
So, we see that there are a few reasons why we may want to supply our own backing field and get/set implementation.
Wrap Up
The .NET property syntax is a bit odd when you first see it, especially if you are coming from a language that doesn't have this type of property implementation. As we've seen, properties are just sets of methods that help us encapsulate our data.
Whether we create our own backing fields or use automatic properties depends on how we're using them. For example, a DTO (Data Transfer Object) is just used to move data around. For these, we can use automatic properties. In contrast, if we have a View Model with properties that need to be databound, we'll probably want to have "full" properties so that we can fire notification events when the values are changed in the setters.
Properties are everywhere, and they are incredibly useful. Hopefully, this has given you a better insight into what's going on "under the covers."
Happy Coding!
Labels:
Automatic Properties,
Backing Fields,
ILDASM,
Properties
Thursday, April 25, 2013
Where Do Curly Braces Belong?
A question came up in one of my sessions this past weekend (Clean Code: Homicidal Maniacs Read Code, Too):
Do you put opening curly braces on the same line or a separate line?
(Let the religious war begin...) So, I gave the answer, "It usually doesn't matter as long as you are consistent." There is an exception for one particular language (which I'll mention below).
The Options
So, let's start by looking at the problem. With any "curly brace" language, we need to decide whether we put the opening curly brace on the same line as the method or conditional, or if we put the curly brace on a separate line. "Curly brace" languages are basically anything that uses C-style syntax, such as C, C++, Java, C#, and JavaScript (there are others as well).
Option one is to put the curly braces on the same line. Here's a sample:
Option two is to put the curly braces on a separate line. Here's a sample:
Each of these styles has its pros and cons. So, let's take a look at the advantages, and I'll let you know my personal preference.
Camp One: Opening Curly Braces on the Same Line
The biggest advantage to having the opening curly brace on the same line is to save vertical space. Vertical density is an important topic when talking about easy-to-read code, so this is definitely something that we should consider.
By having the curly brace on the same line, we reduce the (already short) code sample above by 3 lines. This means that we have more space on the screen to see additional code.
This is also welcome in books and blogs that include code samples since more code can fit in less vertical space.
Camp Two: Opening Curly Braces on a Separate Line
The biggest advantage to having the opening curly brace on a separate line is that the curly braces will always line up visually (assuming that we are also using good horizontal spacing in our code). This makes it easy to visually spot the beginning of the code block -- we just need to find the end brace and then scan up until we see an opening brace in the same column.
Camp Three: K&R
Now, there is a third camp that I should mention just because you may run across it. This is the K&R method (from the book The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie - Amazon link). I recently ran across a curly brace discussion, and they decided that no matter what, K&R is wrong.
I'll have to admit that I didn't know what the K&R method was. When I'm reading books, I generally don't pay attention to curly brace layout. As mentioned above, books often use the "same line" version to save space. So, I went back and took a look through my K&R and was a bit surprised at what I saw.
Here's a sample (based on the same code block from above):
For methods, the opening curly brace is on a separate line. But for other blocks (such as the "if" statement), the curly brace is on the same line.
I think that we can all agree that consistency should be high up on the list So, we'll take K&R off the list of possible choices.
Pick One & Be Consistent
Ultimately, which style we choose doesn't really matter. What's important is that we pick one and stay consistent. Clean Code by Robert C. Martin (Amazon Link + Jeremy's Review) contains a ton of excellent advice. With regard to this topic, there is a section that talks about the importance of vertical spacing and horizontal spacing. Most of the conversation focuses on appropriate blank lines (to break up the code visually) as well as consistent indents (to make code blocks visually apparent).
As with everything else in the development world, we need to find the balance. That's why I don't spend time in my session to talk about this particular topic. People on both sides are extremely passionate about how they do it "the one true way". But really, there are more important things that we should be discussing.
One Exception: JavaScript
There is one exception to the "it doesn't matter" rule: JavaScript. JavaScript has a quirk in the language called semicolon insertion. This means that if the JavaScript parser thinks that you forgot to put a semicolon at the end of a line, it will put one in for you. This can cause problems.
For more information on this, just do some searches for "JavaScript semicolon insertion", and you'll find tons of results. This is also mentioned in JavaScript: The Good Parts by Douglas Crockford (Amazon Link + Jeremy's Review). Of course, he puts this into a section called "The Awful Parts."
So, for JavaScript, we should put our opening curly braces on the same line. Otherwise, we may get unexpected behavior from our code.
Personal Choice
Okay, so you've read through all of this, and I still haven't told you my preference. I like to have the curly braces on a separate line. There are 2 reasons for this.
First, I like that the curly braces line up. This helps me see where the blocks are. (The same was true when I programmed Delphi (Object Pascal) -- I like to have "Begin" and "End" statements line up.)
Second, I'm a lazy programmer. I constantly let Visual Studio reformat my code for me (Ctrl+K, Ctrl+R). The defaults for Visual Studio are to put the opening curly brace on a separate line (unless both curly braces are on the same line -- but that's an entirely different discussion). As a side note, if you get the "Productivity Power Tools" for VS2012, there is an option to have it reformat your code automatically when you save a file; I don't have this turned on.
You can change the way that Visual Studio formats your code; there's a whole slew of options available. This is why I put this into the "lazy programmer" category. For the most part, I run with the Visual Studio defaults (unless there is something that really bugs me). I have a history of moving around to a variety of machines, so I usually have as little customization as possible so that they will all behave the same. (I know, there are ways to export profile settings now, but I'm still stuck in my old ways.)
Wrap Up
I always find it interesting to have these types of discussions with other developers. I like to see who takes it seriously and who sees it as an arbitrary choice. There's also plenty of other people in between.
Pick your battles. In a team environment, we need to make sure that we all work in a consistent manner. Ultimately, where the curly braces go is pretty unimportant compared to other things -- like unit testing strategies.
So, keep your curly braces consistent. And make sure you're using "the one true way." <smirk/>
Happy Coding!
Do you put opening curly braces on the same line or a separate line?
(Let the religious war begin...) So, I gave the answer, "It usually doesn't matter as long as you are consistent." There is an exception for one particular language (which I'll mention below).
The Options
So, let's start by looking at the problem. With any "curly brace" language, we need to decide whether we put the opening curly brace on the same line as the method or conditional, or if we put the curly brace on a separate line. "Curly brace" languages are basically anything that uses C-style syntax, such as C, C++, Java, C#, and JavaScript (there are others as well).
Option one is to put the curly braces on the same line. Here's a sample:
Option two is to put the curly braces on a separate line. Here's a sample:
Each of these styles has its pros and cons. So, let's take a look at the advantages, and I'll let you know my personal preference.
Camp One: Opening Curly Braces on the Same Line
The biggest advantage to having the opening curly brace on the same line is to save vertical space. Vertical density is an important topic when talking about easy-to-read code, so this is definitely something that we should consider.
By having the curly brace on the same line, we reduce the (already short) code sample above by 3 lines. This means that we have more space on the screen to see additional code.
This is also welcome in books and blogs that include code samples since more code can fit in less vertical space.
Camp Two: Opening Curly Braces on a Separate Line
The biggest advantage to having the opening curly brace on a separate line is that the curly braces will always line up visually (assuming that we are also using good horizontal spacing in our code). This makes it easy to visually spot the beginning of the code block -- we just need to find the end brace and then scan up until we see an opening brace in the same column.
Camp Three: K&R
Now, there is a third camp that I should mention just because you may run across it. This is the K&R method (from the book The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie - Amazon link). I recently ran across a curly brace discussion, and they decided that no matter what, K&R is wrong.
I'll have to admit that I didn't know what the K&R method was. When I'm reading books, I generally don't pay attention to curly brace layout. As mentioned above, books often use the "same line" version to save space. So, I went back and took a look through my K&R and was a bit surprised at what I saw.
Here's a sample (based on the same code block from above):
For methods, the opening curly brace is on a separate line. But for other blocks (such as the "if" statement), the curly brace is on the same line.
I think that we can all agree that consistency should be high up on the list So, we'll take K&R off the list of possible choices.
Pick One & Be Consistent
Ultimately, which style we choose doesn't really matter. What's important is that we pick one and stay consistent. Clean Code by Robert C. Martin (Amazon Link + Jeremy's Review) contains a ton of excellent advice. With regard to this topic, there is a section that talks about the importance of vertical spacing and horizontal spacing. Most of the conversation focuses on appropriate blank lines (to break up the code visually) as well as consistent indents (to make code blocks visually apparent).
As with everything else in the development world, we need to find the balance. That's why I don't spend time in my session to talk about this particular topic. People on both sides are extremely passionate about how they do it "the one true way". But really, there are more important things that we should be discussing.
One Exception: JavaScript
There is one exception to the "it doesn't matter" rule: JavaScript. JavaScript has a quirk in the language called semicolon insertion. This means that if the JavaScript parser thinks that you forgot to put a semicolon at the end of a line, it will put one in for you. This can cause problems.
For more information on this, just do some searches for "JavaScript semicolon insertion", and you'll find tons of results. This is also mentioned in JavaScript: The Good Parts by Douglas Crockford (Amazon Link + Jeremy's Review). Of course, he puts this into a section called "The Awful Parts."
So, for JavaScript, we should put our opening curly braces on the same line. Otherwise, we may get unexpected behavior from our code.
Personal Choice
Okay, so you've read through all of this, and I still haven't told you my preference. I like to have the curly braces on a separate line. There are 2 reasons for this.
First, I like that the curly braces line up. This helps me see where the blocks are. (The same was true when I programmed Delphi (Object Pascal) -- I like to have "Begin" and "End" statements line up.)
Second, I'm a lazy programmer. I constantly let Visual Studio reformat my code for me (Ctrl+K, Ctrl+R). The defaults for Visual Studio are to put the opening curly brace on a separate line (unless both curly braces are on the same line -- but that's an entirely different discussion). As a side note, if you get the "Productivity Power Tools" for VS2012, there is an option to have it reformat your code automatically when you save a file; I don't have this turned on.
You can change the way that Visual Studio formats your code; there's a whole slew of options available. This is why I put this into the "lazy programmer" category. For the most part, I run with the Visual Studio defaults (unless there is something that really bugs me). I have a history of moving around to a variety of machines, so I usually have as little customization as possible so that they will all behave the same. (I know, there are ways to export profile settings now, but I'm still stuck in my old ways.)
Wrap Up
I always find it interesting to have these types of discussions with other developers. I like to see who takes it seriously and who sees it as an arbitrary choice. There's also plenty of other people in between.
Pick your battles. In a team environment, we need to make sure that we all work in a consistent manner. Ultimately, where the curly braces go is pretty unimportant compared to other things -- like unit testing strategies.
So, keep your curly braces consistent. And make sure you're using "the one true way." <smirk/>
Happy Coding!
Labels:
Clean Code
Subscribe to:
Posts (Atom)















