Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for C#

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!
May 16, 2014

What is Defensive Coding?

Filed under: C#,Testing,VB.NET @ 10:40 am

From Wikipedia (as of 4/14/14):

… an approach to improve software and source code, in terms of:

General quality – Reducing the number of software bugs and problems.

• Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit.

• Making the software behave in a predictable manner despite unexpected inputs or user actions.

Let’s consider each of these bullet points…

General quality

Coding defensively means to actively code to reduce bugs. One of the key techniques for improving quality is through automated code testing.

Don’t know that you have time in your project schedule for automated code testing? That’s a topic for another blog post. Or check out my “Defensive Coding” course referenced at the bottom of this post for a demonstration of some simple automated code testing techniques and a discussion of the “no time for testing” issue.

Comprehensible

It is not just computers that need to read and understand your code … people need to read and understand it as well.

If another developer doesn’t understand your intent, they may make incorrect assumptions about that code and make inappropriate code changes … causing your code to fail.

Plus if the code is easy to read and understand, it will be easier and less time consuming to modify as the application is maintained or enhanced over time.

The key to making source code more readable and understandable is by building “Clean Code”. The concept of “Clean Code” was first presented by Robert Martin in his book: “Clean Code: A Handbook of Agile Software Craftsmanship”.

The cleaner your code is, the easier it is to understand, maintain, and test.

Predictable

Predictable code should handle unexpected inputs or user actions by anticipating them and responding accordingly.

This includes techniques such as guard clauses, validation, and error handlers.

Putting these three concepts into a picture summarizes the goals of defensive coding:

image

For more information on Defensive Coding, see my Pluralsight course: “Defensive Coding in C#”.

Enjoy!

PS-circle22

 

Check out my Pluralsight courses!

May 9, 2014

Defensive Coding in C# Course Went Live Today!

Filed under: C#,Visual Studio @ 11:45 am

How do you write great, maintainable code when faced with constantly changing requirements, legacy issues, intensive time pressures and a rapidly evolving environment? And how do you keep that code great after maintenance activities, multiple developers, and the ravages of time?

My new Pluralsight course: Defensive Coding in C# shows you how to write great, maintainable code and keep that code great using defensive coding techniques.

image

Enjoy!

PS-circle22

 

Check out my Pluralsight courses!

May 7, 2014

Does Your Code Feel Like a Ball and Chain?

Filed under: C#,VB.NET,Visual Studio @ 11:06 am

Do you ever work on code that is disorganized; that was too often written the “quick” way instead of the “right” way? You try to make one little change or addition and the existing code makes everything difficult. The code feels like a ball and chain, dragging you down and slowing your progress.

image

If you have experienced this phenomenon, you have seen the results of technical debt.

Pluralsight just released a new course from Mark Heath entitled “Understanding and Eliminating Technical Debt“. It explores what technical debt is, the problems it causes, and how you can identify and quantify it. Then, the important bit, it shows you how to create an action plan to address the technical debt and provides some practical techniques for repaying it.

image

I’ve just watched this course and HIGHLY recommend it for any developer.

Enjoy!

PS-circle2

 

Check out my Pluralsight courses!

February 18, 2014

I’m Looking for a .NET Project

Filed under: C#,VB.NET,Visual Studio @ 2:16 pm

I recently completed a .NET project for a client I had been working with since November of 2009 … over 4 years.

It was great fun to help them build their system: client Point of Sale, Silverlight (MVVM/XAML) management package, Web API/JQuery customer facing application, WinForms support tool, over 2100 automated code tests and all of the parts in between. I will greatly miss this code (and my wonderful client of course)!

I am looking for my next .NET project, large or small. I am great at turning nebulous requirements into a successful application. I have experience working in a team or as the sole developer; training and mentoring developers; refactoring existing or building new applications; and using an iterative development approach for a quicker time to market. And I’ve recently been working with JavaScript frameworks such as AngularJS, Backbone and Knockout.

I am located in the Silicon Valley/San Francisco Bay area, but can telecommute to anywhere. (My last several clients required telecommuting, including one in northern California and one in eastern Canada.)

Pass along this link if you know of someone that could use an experienced .NET developer / consultant on a full-time, part-time or one-time basis.

Thanks!

Email to deborahk at insteptech dotcom

February 17, 2014

Technical Debt of Using Code Behind

Filed under: C#,VB.NET,Visual Studio @ 6:25 pm

I recently wrote a post entitled "Why Use Code Behind?". It outlined several reasons why .NET developers use code behind for the logic of their C# or VB.NET applications, not just for UI management.

This post looks at the down side of using code behind for application logic … in two words: Technical Debt.

From Wikipedia:

"The debt can be thought of as work that needs to be done before a particular job can be considered complete. If the debt is not repaid, then it will keep on accumulating interest, making it hard to implement changes later on. Unaddressed technical debt increases software entropy."

From Ward Cunningham, 1992 (as quoted in Wikipedia):

"Shipping first time code is like going into debt. A little debt speeds development so long as it is paid back promptly with a rewrite… The danger occurs when the debt is not repaid. Every minute spent on not-quite-right code counts as interest on that debt."

Bottom line … using code behind for the logic of an application adds to your technical debt.

Some situations, such as when building a Minimum Viable Product, incurring technical debit is a logical choice. Why not incur debt if the team is not even sure if they are building the right thing?

In other situations, the team may not be aware of the technical debt they are accumulating. Not until the application complexity, testing process, or bug count become unacceptable, or worse the project fails.

Two areas where technical debt becomes apparent are maintenance and testing.

Maintenance

In most cases, writing the initial code is only but a fraction of the lifetime of that code. The vast majority of time is spent on extending, enhancing, modifying, or fixing it.

Writing application logic in the code behind makes maintenance much more difficult (adding interest on the debt). Code behind:

  • Prevents Reuse. For example, say a developer has code in code behind that opens a file. If a later feature also needs that same logic, it will need a copy/paste to reuse it.
  • Encourages Duplicate code. See the prior example. And if a bug is later found in a routine, will the bug in the copies be found and fixed?
  • Adds Complexity. Instead of working with many small routines that each perform one task, code behind often leads to writing very long methods that contain all of the logic required for a particular event. For example, a Save button’s code behind might perform validation, create a transaction, save to the database, generate an email, and print a receipt.
  • Prevents Automated Code Testing. See the next section.

By writing logic in components, those components can be reused, preventing duplication. And the methods within the components can be single-purpose, making them less complex and easier to maintain and test.

Automated Code Testing

Writing code without unit tests adds to the interest on the technical debt … and not like a home mortgage 3 or 4% interest … more like a credit card’s 35% interest or more. Let’s look at why…

A developer builds a feature and provides it to someone else for testing. That tester may spend many hours testing all of the possible paths through the code. The code is released and work starts on the next set of tasks.

When that work is finished, the tester needs to test every single path again:  all of the original code paths plus all of the new ones.

In most cases, the developer ran over the schedule, so the testing schedule is cut. The tester needs to test more in less time. And over time, the number of paths to test grows.

Using the built-in MSTest tools or any testing tools compatible with Visual Studio, such as NUnit, you can easily create automated code tests for your logic. But not if that logic is hidden inside a code behind file.

By writing the code in components, the developer can use the automated code testing tools within Visual Studio to test the application logic. And more exciting … the developer can easily retest all of the original functionality with those tests as the code changes over time.

Your thoughts?

February 12, 2014

My Latest Course Went Live Today!

I am happy to announce that my latest Pluralsight course: "Visual Studio Data Tools for Developers" went live today!

As C# or VB.NET developers, we often need to work with a database.

This course covers how to:

  • Use the many SQL Server Data Tools (SSDT) in Visual Studio
  • Manage SQL Server databases with Visual Studio
  • Build database scripts (including data scripts) with a Database Project
  • Publish Database Scripts
  • Unit Test stored procedures
  • Generate a DACPAC
  • Use a DACPAC to deploy database changes

You NEVER have to write database change scripts again!

Check it out and let me know what you think! Feel free to leave comments here or in the Discussion section for the course.

http://www.pluralsight.com/training/Courses/TableOfContents/visual-studio-data-tools-developers

image

Enjoy!

Next Page »

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