Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

Get GitHub Code

This lesson deals with building cohesive, conceptually sound class structures for readability and maintainability. Start off by creating an ASP.NET project with a Default.aspx file.

Step 1: Adding a Class File to the Project

In the previous lesson, we learned how to create multiple classes that exist side-by-side within the same file, and under a common namespace outer container. While this can be useful for quickly testing out code and keeping it easy to reach, larger applications will make this impractical. In these cases, it is often preferable to separate classes into their own files. You can add a class to the project by right-clicking on it from within the Solution Explorer, and selecting from the context menu:


From the resulting context menu select:

Add > New Item…

And in the dialogue, choose the “Class” item under the “Visual C#” tab:


To help keep track of what classes are in your Class files, you would typically want to name the file the same as the class itself. In this case, we are going to create an Automobile class:



Open up this Class file and write out the following code for it, omitting the method implementation details for now:




It can be difficult for beginners to quickly glimpse the constituents of a large class and separate the properties from the methods, especially if a method has a return type. When scanning through the class, try to look for the parentheses, such as in DetermineMarketValue(), as a “dead giveaway” that the member is a method. Also, although not strictly enforced, the rule of thumb is that properties are at the top of the class, and below that are the methods.

Step 2: Prelude to Understanding Accessibility Modifiers

And now, in the Default class, create an instance of the Automobile class and set its properties, along with calling some of its (empty) methods:


Notice that even though each of these classes are in their own separate files, they are able to “see” each other and that is because they share the same namespace. Also, note that even though the Automobile class is not marked as “public” it is still available to other classes within the namespace. This is because in absence of an accessibility modifier, it defaults to accessibility level called “internal” (meaning internally accessible to this namespace only):



Step 3: Keeping Classes Lean

Going back to the Automobile class, notice how large it is (even without any real implementation details). When you consider how this class is structured (presumably in anticipation of fulfilling a need within a broader application) it may, seem like the class is highly cohesive and sticks to the single responsibility principle. However, just because all of these methods and properties have something to do with a car, doesn’t mean they should all belong in the Automobile class. For example, this set of properties refer to a buyer’s details so perhaps it’s best to have these within a separate class:


Go through the remaining list of properties and methods and try to anticipate which items are best moved into other classes.


There is a rule of thumb that some software developers subscribe to that says every class should be no longer than the length of the screen its being viewed on (setting aside that screen and font sizes aren’t uniform). In other words, you shouldn’t have to scroll down to see the rest of the code in the class. While simplistic, the wisdom here again is to keep the principle of Single Responsibility in mind and break up a single large class into a bunch of smaller classes whenever possible.

Let’s apply what we’ve learned about code refactoring from previous lessons to break up this single, monolithic, Automobile class into a series of smaller classes - each within their own file within the Solution Explorer:



The purpose of having highly "cohesive" classes is to reinforce the single responsibility principle we've discussed before. Cohesive classes have properties and methods that are directly related to each other. Other extraneous details or functions can be moved to other, more cohesive classes. This allows you, the programmer, to create an application that can withstand time and change in the architecture of the program. We'll discuss architecture later, but think of the way that short, specific methods allow you to affect the functionality of the program without modifying its core components on a larger scale.

Here is how each individual class now breaks down (again, the implementation details are not important, just focus on the way the classes are restructured):










Step 4: Organizing Classes in Folders

While having many small, cohesive classes is preferred to just a few large classes, organization can become an issue. A useful organizational technique is to group class files into folders relative to their problem domain. This is especially useful when a project grows larger and you need to locate a class in order to update it, and so on. Simply right click on the Solution Explorer and select:

Add > New Folder

And after you name the folder you can select all of the class files you want to have added to this folder and drag/drop right into it. Here we labeled this folder as “Domain” to signify the domain layer of concern. However, as you move forward you can separate into other folders that represent other conceptual layers of your codebase:


Step 5: Using Visual Studio to Navigate Classes

While on the topic of navigating within your project there are some tools Visual Studio provides to aid this task. There are list boxes at the top of the main window that let you move between various (1) projects, (2) classes, as well as their (3) fields and properties:


Step 6: ‘Go To Definition’ to Review a Class

Another handy tool is the ability to navigate to a class definition by right-clicking wherever that class is referenced and selecting either “Peek Definition” (displays class inline) or “Go To Definition” (jumps to class):


You can also navigate to different classes by clicking on the downward arrow in the upper-right corner of the main window:


Step 7: Find All References of a Class the Project

The flip-side of finding a class definition would be to find all instances of the class within your project. You can right-click on the class name once again and this time select “Find All References”:


A window will pop-up describing where the class is being referenced (jump to the line of code with the reference by clicking on the line shown):


Step 8: Docking Windows for Code Comparison

Sometimes you want to compare information between, and within, different classes. To satisfy this you can have multiple windows open by clicking/dragging tabs anywhere on the screen and hovering over the multiple docking options available (here it docks to a horizontal window below the existing main window):




You can use this docking system with just about any window within Visual Studio in order to customize it to your needs.

Step 9: Customizing Docked Windows

Also, be aware that this icon in the upper right-hand corner of the main window lets you split a window into two windows so that you can view different parts of the same class, each within its own window, for instance:


You can also right-click on any tab and select whether or not you want to move it another vertical/horizontal tab group:



Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment