Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for C#

February 24, 2016

Understanding C# Delegates

Filed under: C#,LINQ @ 12:10 pm
Tags:

Delegates are sometimes seen as an ethereal concept, bodiless and hard to grasp. But they don’t have to be that way.

In my latest Pluralsight course: “C# Best Practices: Collections and Generics“, I walk through what a delegate is and how to understand them.

image

A delegate is simply a type that represents a reference to a method with a specific parameter list and return type. The primary purpose of delegates is to pass methods as arguments to other methods.

Here is an example of a method that needs a delegate:

var filteredList = vendors.Where(???);

In the above line of code, we use the LINQ Where method to filter a list of vendors. The Where method needs a selector defining the logic to be used for the filtering. Do we want to filter the list of vendors by some keyword in their name? Or by how much they currently owe us? Or by the product types that they sell? Somehow we need to specify this logic. We do that with a method.

What does that method need to look like? In Visual Studio, Intellisense shows us the signature of the delegate method that it needs. For the LINQ Where method, it is:

vendors.Where(Func<Vendor, bool> predicate)

Let’s break down what Intellisense is telling us here:

  • The “Func” specifies that the method we create has to return a value. If the method does not require a return value, the Intellisense will instead say “Action”.
  • The first generic parameter (Vendor in this example) is the first parameter to the method we create.
  • If there is a return value, the last generic parameter (bool in this example) defines the return value type.

So looking at the example, we know we need to create a method with a bool return value that takes one parameter of type Vendor.

We can then create a method such as this:

private bool FilterCompanies(Vendor v)
{
   return v.CompanyName.Contains(“Toy”);
}

This method takes in a Vendor object and returns a Boolean. Specifically, it returns true if the vendor’s company name contains “Toy”. Otherwise it returns false, thereby specifying how we want the vendor list filtered.

We can then pass this method as a delegate to the Where method:

var filteredList = vendors.Where(FilterCompanies);

The resulting filteredList contains the list of vendors whose company name contains “Toy”.

The problem with this approach is that we end up with little methods all over that simply define these delegates. There is another way. We can use Lambda Expressions. Lambda Expressions are basically a short cut syntax for these little methods.

So instead of this:

var filteredList = vendors.Where(FilterCompanies);

private bool FilterCompanies(Vendor v)
{
   return v.CompanyName.Contains(“Toy”);
}

We can simply type this:

var filteredList = vendors.Where(v => v.CompanyName.Contains(“Toy”));

For more information, check out: “C# Best Practices: Collections and Generics” from Pluralsight.

Enjoy!

January 28, 2016

C# Best Practices: Collections and Generics

Filed under: C#,Lambda Expressions,LINQ @ 12:27 pm

The next in my series of “Best Practices” courses was published today in the Pluralsight library: “C# Best Practices: Collections and Generics“.

This course starts with the classic collection type: arrays. Then it moves on to generics … that challenging to explain topic that often shows up even in the most basic of beginner courses … because without generics we don’t have a good way to work with collections of things. And most applications require working with collections of things.

image

We move on to cover generic lists and generic dictionaries. Then we dive deeper into generic collections, looking at the interfaces they implement and how to leverage those interfaces as method parameters and return types.

image

Lastly, we look at Language Integrated Query (or LINQ) for filtering, shaping, ordering, grouping, aggregating, or locating elements in a collection. Along the way we cover extension methods, delegates, and Lambda expressions.

image

Enjoy!

January 21, 2016

Dividing a C# Application into Components

Filed under: C# @ 2:52 pm
Tags: , ,

A good architecture divides an application into components:

  • We build UI classes in the UI layer
  • Domain entity classes in the business logic layer
  • Data access classes in the data access layer.
  • And library classes in the common library component.

The content for this blog post was taken from the Pluralsight course entitled “C# Best Practices: Improving on the Basics“. Check out this course for more information.

image

UI Layer

When we add a form to a UI component, such as a Windows Forms, WPF, or a Web Forms project, Visual Studio automatically creates a form class for us. So our application will have one class for each form. The form class should contain code that:

  • Responds to form events by calling the business logic layer to perform needed processing.
  • Includes error handling for any errors that occur.

There is another type of class that you may find in the UI layer, and that is a V/M or View/Model class. A View/Model manages the data and interaction for a single form or view. A View/Model class is often used in cases where the user interface can bind directly to data defined in the View/Model class, such as with WPF.

 

Business Logic Layer

When defining classes for the business logic of an application we can start by defining a domain model. A domain model identifies the basic business entities to be managed by the application and how they are related.

image

For example, if Acme Inc needs a feature to order more product inventory from a vendor, we can define a domain model that includes

  • An order.
  • The product to order. So the order “has a” product.
  • And the vendor from whom the company buys that product. So the product “has a” vendor.

We can use the domain model as a starting point for defining the classes in the business logic component. We’ll need a class to manage each order, a class to manage product information, and a class that manages each approved vendor.

Defining the domain model helps us to consider all of the different bits of logic that the application will require and organize that logic into appropriate classes.

Also in the business logic layer we may want Repository classes. Repository classes are responsible for managing the in memory repository of data for the application. For example, when the user requests display of a specific vendor and the products purchased from that vendor, the Repository classes are responsible for getting that data, tracking the state of that data (for example, whether it has been changed) and saving that data using the data access layer.

 

Data Access Layer

The classes in the data access layer depend on the data access strategy you are using. If you are using Entity Framework, you may not need any classes in this layer because Entity Framework defines them for you.

Common Library Component

We can determine whether specific functionality goes into a library component by looking at the other components. If the functionality is common across layers (or across applications), then it may be better in a library component. For example, code that provides logging, or sends out email.

 

Conclusion

When is it appropriate to divide an application into components and define classes such as these? Maybe always? Even if we are developing a prototype, way too often that prototype becomes the basis of our real application.

By breaking the application into a set of components early on in the development cycle we start with a strong foundation that can support the application as it grows and changes over time.

Enjoy!

January 15, 2015

Visual Studio 2015: A First Look at the IDE

Filed under: C#,Visual Studio @ 7:23 am

My course on Visual Studio 2015 just went live today on Pluralsight: “Visual Studio 2015: A First Look at the IDE“.

(If you don’t have a Pluralsight membership, sign up for a free trial here.)

image

This course covers:

  • Coding assistance with the new Light Bulb icon
  • Renaming and refactoring enhancements
  • Debugging improvements
  • Layout customization features
  • Touch gestures
  • XAML Peek Definition
  • Feedback changes
  • CodeLens Enhancements

Enjoy!

January 6, 2015

MSDN Now Includes Pluralsight Courses

Filed under: C#,Visual Studio @ 11:53 am
Tags: ,

In November of 2014, Microsoft announced that subscribers will receive a 12-month Pluralsight training benefit as part of its MSDN subscription. So if your New Year’s resolution was to update/enhance your development skills, this offer can help.

The number of courses included in this benefit depend on the type of MSDN subscription. As an example, my particular subscription includes 30 courses as shown below.

image

This set of course includes three of mine, as indicated above and described below.

Mastering Visual Studio 2013 focuses on the new features added to 2013 including Peek Definition, the enhanced scroll bar, Navigate To improvements, XAML editing enhancements, and CodeLen. This course is great if you are already using Visual Studio and want an update on the latest tools and editing features VS 2013 provides.

Visual Studio Data Tools for Developers is all about using SQL Server Data Tools (SSDT) in Visual Studio. This course is for you if you use SQL Server and Visual Studio and want to learn how to build database projects, check in database scripts, and easily deploy database changes using SSDT.

Defensive Coding in C# is for C# developers that want to write clean, maintainable, and testable code … and keep that code great even in the face of changing requirements, multiple developers, and the passing of time.

To activate your benefit:

  1. Log into your MSDN account.
  2. Select to activate your Pluralsight benefit:

image

Enjoy!

November 7, 2014

"Getting to Great With C#": A Learning Path

Filed under: C# @ 9:31 am
Tags: , , ,

As developers, we are always looking for ways to hone our skills. If you are a C# developer, there are many paths to take. That is where a learning path can help.

A learning path provides a specific set of recommendations for enhancing your C# development skills. The “Getting to Great with C#” learning path shows you how to use the C# language to build well-crafted applications. It focuses less on language features and more on good programming practices and techniques. So if you are already familiar with C# and are looking to elevate your skills, check out this learning path.

image

These map to the following Pluralsight courses:

Course Duration
Object-Oriented Programming Fundamentals in C# 4h 22m
Defensive Coding in C# 4h 32m
Clean Code: Writing Code for Humans 3h 10m
C# Interfaces 2h 52m
Abstract Art: Getting Things “Just Right” 2h 08m
Dependency Injection On-Ramp 2h 38m
SOLID Principles of Object Oriented Design 4h 08m
Design Patterns On-Ramp 3h 31m
Design Patterns Library 15h 01m

See this blog post for more information on this learning path.

Enjoy!

September 19, 2014

Object-Oriented Programming (OOP) Terms

Filed under: C#,OOP @ 10:22 am

I recently completed a course for Pluralsight entitled “Object-Oriented Programming Fundamentals in C#.” In that course, I cover OOP concepts and definitions of common OOP terms. In the discussion board for that course, someone suggested a “cheat sheet” that summarized the definitions. So here it is:

Basics

Object-Oriented Programming (OOP): An approach to designing and building applications that are flexible, natural, well-crafted, and testable by focusing on objects that interact cleanly with one another.

Class: The code describing a particular entity in the application, such as Customer, Order, or Address. The class contains the code defining the properties and methods (see below).

Property: The code defining the data managed by the class, such as CustomerName, OrderNumber, or EmailAddress.

Method: The code defining the actions or behaviors of the class, such as Validate or CalculateTotal. Methods are defined in the code with C# functions.

Members: Refers to the properties and methods for a class.

Object: An instance of a class that is created at runtime. In C#, an instance is created with the new keyword.

Object Variable: The variable used when creating an object. For example, var myCustomer = new Customer(); In this example, myCustomer is the object variable. Use the object variable to set the properties and call the methods. The object variable retains the state of the object.

Method signature: The code defining the method function including the function name and the set of parameters. The signature does not include the return type. Every function signature within a class must be unique. The signature is used to “match up” calls to the function.

Overloading: Methods that have the same name but different parameters. Example: public bool Retrieve() and public bool Retrieve(int id). The Retrieve method in this example is said to have “two overloads”.

Contract: The set of public properties and methods in a class define the classes contract. The class makes a promise that it will provide the defined properties and methods to any other code that needs them. This is also known as the “class interface“.

Constructor: Code that is executed each time an instance of the class is created.

Default Constructor: A constructor with no parameters.

Overriding: When using inheritance (see below), a child class can override a member of the parent class to provide its own implementation.

Interface: An explicit interface is a separate type (INotifyPropertyChanged for example) that defines a set of properties and methods with no implementation. Any class can then implement an interface to use the set of properties and methods provided in the interface. Think of an interface as a role that an object can play. For example, an ILoggable interface defines a logging role. An IEmail interface defines an emailing role. An Order class may implement both the ILoggable and IEmail interface to take on both roles. An Address class may implement only the ILoggable interface.

Four Pillars of Object-Oriented Programming

The pillars of OOP define the key characteristics of object-oriented programming and are:

Abstraction: The process of defining classes by simplifying reality, ignoring extraneous details, and focusing on what is important for a purpose. For example, a customer may have a name, title, address, marital status, pets, children, credit card information, vehicles, etc. But if the purpose of the application is to process orders, the application may only care about the customer’s name, address, and credit card information.

Encapsulation: A way to hide (or encapsulate) the data and implementation details within a class, thus hiding complexity. In C#, data elements are defined with private backing fields and exposed through property getters and setters. So the data is encapsulated.

Inheritance: A relationship between classes whereby child (or derived) classes inherit all of the members of the parent (or base) class. For example, an application may define a “business object base” class that all business objects inherit from. This base class can contain members common to all child classes, such as entity state information.

Polymorphism: Basically “many forms”. The concept that a single method can behave differently depending on the type of object that calls it. For example, the Validate method in Customer class performs differently from the Validate method in the Order class.

Inheritance-Based Polymorphism: Polymorphism in the case where the method is defined in a base class and behaves differently for each child class.

Interface-Based Polymorphism: Polymorphism in the case where the method is defined in an interface and behaves differently in each class that implements the interface.

Class Relationships

Collaboration: “Uses a” relationship. Objects can collaborate with other objects. For example: Customer Repository “uses a” Customer object to populate on a retrieve and serialize on a save.

Composition: “Has a” relationship. Objects can be composed of other objects. For example, Order “has a” Customer and Order “has a” shipping address.

Inheritance: “Is a” relationship. Objects can be subtyped. For example, a Business Type Customer “is a” Customer and a Residential Type Customer “is a” Customer.

C# OOP Terms

Auto-implemented properties: Properties that create and manage the encapsulated backing field automatically.

Static method: Adding the static modifier on a member of the class (property or method) defines that the member belongs to the class itself, not an instance of the class.

Sealed class: Class that cannot be used as a base class for an inheritance relationship.

Abstract class: Class that cannot be instantiated, so no objects can be created from the class. Nor can it be accessed by its class name. The class can only be used as a base class for other classes.

Concrete class: Class that can be instantiated. Basically, the opposite of an abstract class.

Static class: Class that cannot be instantiated, so no objects can be created from the class. The class members are instead accessed using the class name. A static class provides a shortcut to the members of the class when instancing is unwarranted. For example, the .NET Framework Console class is a static class. To call the WriteLine method you use Console.WriteLine. You don’t have to create a new instance of Console.

Abstract method: Method with no implementation (basically no code). The method must be overridden by a child class.

Virtual method: Method with an implementation that can be overridden by a child class.

For More Information

For more information and detailed coding examples for these concepts/terms, check out the course.

Enjoy!

September 5, 2014

Abstract Class vs Interface

Filed under: C#,OOP @ 5:10 pm

Since publishing my course on Object-Oriented Programming Fundamentals in C# for Pluralsight, I often receive questions from viewers. One of the common questions is on the difference between an Abstract Class and an Interface.

Abstract Class

An abstract class is a class that cannot be instantiated, meaning you can’t use the new keyword to create one. Some key qualities of an abstract class:

  • It is intended to be used as a base class for other classes that inherit from it.
  • It can provide implementation, meaning that it can contain the code for an operation.

For example, you could define an abstract product base class:

public abstract class ProductBase

{

   public bool Save {

       // Code here to save the product

   }

}

The Save method here would contain the code to save a product.

You could then create specialized product classes: BookProduct, GroceryProduct, and OfficeProduct. Each of these specialized classes inherit from the ProductBase class. The specialized product classes then don’t need to contain the logic for the save, because it is provided in the base class.

Say you then define another abstract class for logging.

public abstract class Logging

{

   public void Log{

       // Code here to log information

   }

}

You need the logging functionality in the BookProduct class. Since C# does not allow multiple inheritance, the BookProduct class cannot inherit from *both* the ProductBase class and the Logging class. You instead have to create a hierarchy:

BookProduct class inherits from ProductBase class which inherits from the Logging class.

GroceryProduct class also inherits from ProductBase class which now inherits from the Logging class. So even if the GroceryProduct class does not want or need logging, it still has all of the logging features because Logging is part of its class hierarchy.

This can lead to deep inheritance chains that make the code more complex and difficult to maintain/extend.

Interface

An interface is a set of properties and methods. You can think of an interface as a contract whereby if a class implements the interface, it promises to implement *all* of the properties and methods in the interface. Some key qualities of an interface:

  • It is intended to be implemented by other classes. Each class that implements the interface promises to provide code for each property and method in the interface.
  • An interface cannot contain any implementation, meaning that it does not contain any code, just declarations.

Using the same example as above, you could define IProduct:

   public interface IProduct{

       bool Save();

   }

This interface cannot contain any code for the save. So each product class (BookProduct, GroceryProduct, and OfficeProduct) would need to implement this interface and provide its own code for the save feature.

Say you then define an interface for logging.

   public interface ILoggable{

       void Log();

   }

Any of the product classes that need logging can implement this interface. You can think of an interface as defining a role that a class can take on. For example, the BookProduct class could take on a logging role, email role, and printing role by implementing a logging interface, email interface, and printing interface.

By using an interface:

  • Only the specialized product classes that need logging can implement the ILoggable interface.
  • Each product class that does implement the ILoggable interface needs to provide its own implementation.
  • Other classes (completely unrelated to products) can use the ILoggable interface. The class does not need to be defined within the same hierarchy.

Summary

You can think of an abstract class as a bucket of functionality shared by all of your relatives. And an interface as a role that anyone in the community can take on.

Use an abstract class if:

  • You are building a base class.
  • You want to provide code that the specialized child classes could use (or override)
  • You don’t need the functionality in the abstract class for any classes other than those within the class hierarchy.

Use an interface if:

  • You are defining a “role” that a class could take on.
  • You may want to use the interface on unrelated classes.
  • Each class implementing the interface will provide an implementation.

Thoughts? Questions? Please use the space below to submit your comments.

Enjoy!

PS circle

Check out my Pluralsight courses!

June 4, 2014

"I Don’t Have Time for Unit Testing!"

Filed under: C#,Testing,VB.NET @ 12:50 pm

So, be honest, when you hear someone talk about unit testing … what is your first thought?

  • Is it: “I just don’t have the time to do unit testing”!
  • Or “Our management will never approve the time for unit testing”?
  • Or something similar?

Let’s look at what unit testing can do for you:

Save you Time

Yes, that’s right!

Throughout my career as a software developer, I have seen how much time unit tests can save.

Let’s think about this …

  • Any developer that has written more than a few lines of code knows that it needs to be run to verify that it operates as expected. Right?
  • You need to execute the feature to confirm that it takes appropriate inputs and produces appropriate outputs. You may need to go through this process several times.
  • And as you build more features, it requires more effort to manually test it.
  • For example, say you write a pedometer application that takes in a step count goal and an actual step count and then calculates the percent of goal you have reached.
    • To test the pedometer feature you need to execute the application, navigate to the appropriate feature, enter all of the required data, and then validate the results.
    • And if you find a bug you may have to repeat this process again, and again, and again.
    • For the feature you are working on now, how many times have you run the application to try it out? 10? 20? more?
  • The idea of an automated code test is that you can write code to perform that testing.
  • So if you want to test that the pedometer calculation is correct, you write an automated code test that defines appropriate inputs, calls the function under test, and verifies the results.
  • Then when the users want a change to that code (and you know that they will), you can make the change and just re-run the tests.
  • No need to slog through the UI again for each possible set of inputs.

This can save you LOTS of time.

Help you Find Bugs Faster

You just received a bug report. Something in the code does not work.

Instead of trying to reproduce the problem by wading through a bunch of UI, you can instead use your unit tests to quickly reproduce, find, and fix the error.

Allow you to Refactor Safely

So you are working on some code that is just too painful to deal with.

You’d like to apply some refactoring techniques to make the code cleaner and easier to use.

With no tests, you are running a risk of introducing bugs if you rework the code.

If you have unit tests in place, you can safely perform a refactoring because when you are done with the refactoring, you can rerun the tests to confirm that all is well.

Readily Add Features

You can add new features and rerun all of the existing tests to ensure that the new feature does not adversely impact any existing features.

No more worry that adding feature b will adversely affect feature a.

Minimize Those Annoying Interruptions

So you are in the middle of coding the next feature and you have to drop everything because someone entered something bad somewhere in your application and now it is crashing.

Bummer!

Having a good set of unit tests can minimize those annoying interruptions.

Enhance your Value

Don’t you just hate it when the “QA” person emails you to let you know your code doesn’t work?

This is especially difficult if that “QA” person if your boss or your client.

Having a good set of unit tests can make you look like a coding master!

Or what if the person after you changes something and now it looks like your code doesn’t work.

Unit tests help the developers that come after you to better understand and modify your code. They can re-run the tests to ensure the code still works after their changes.

Having a good set of unit tests verifies that your code works over the lifetime of the application.

Conclusion

Writing unit tests isn’t hard or time consuming once you get into the habit. And these benefits look pretty good!

For a gentle introduction to automated code testing, see my Pluralsight course: “Defensive Coding in C#”.

Enjoy!

PS circleCheck out my Pluralsight courses!

Code Quality and Automated Code Testing

Filed under: C#,Testing,VB.NET @ 12:31 pm

I’ve heard it said that the top three techniques for improving code quality are:

  • Unit testing
  • Unit testing
  • Unit testing

There is no better defense for the quality of your code than a set of automated code tests.

Automated code testing involves exercising code and testing its behavior by writing more code. So you have a set of code that tests your original code.

The goal of unit testing is to isolate each unit of code in an application and verify that the unit of code behaves as expected in both valid and invalid conditions.

To achieve this goal, we can:

  • Refactor our code where necessary into individual units (methods) that can be tested.
  • Create a set of tests for each method.
    • Tests with valid inputs.
    • Tests with invalid inputs.
    • Tests that could produce exceptions.
  • Execute those tests using a testing framework, such as MSTest or NUnit, both of which are executable from with Visual Studio (ALL editions, including the free Express edition!)

Don’t have time to test? See this post!

For a gentle introduction to automated code testing, see my Pluralsight course: “Defensive Coding in C#”.

This is what one reviewer said about the “Automated Code Testing” module of this course:

This module is an excellent introduction to unit testing with C#!

In fact it should be recommended to C# subscribers as the first place to go to learn about unit testing, before they take any of the .NET unit testing courses in the library. For many this is all they will need,

It takes a viewer on a clear path from zero-knowledge about unit testing to being able to doing useful, real development, unit testing in 45 minutes.

It does a very good job of covering both the mechanics and how to make practical use unit testing.

Enjoy!

PS circleCheck out my Pluralsight courses!

Next Page »

© 2016 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs