title
stringlengths
3
46
content
stringlengths
0
1.6k
4:134
var messageResponse = ProcessCreditCardMethod();
4:135
Dictionary<CreditCardProcessingResult, CheckResultMethod>
4:136
methodsForCheckingResult = GetMethodsForCheckingResult();
4:137
if (methodsForCheckingResult.ContainsKey(messageResponse))
4:138
methodsForCheckingResult[messageResponse](billingMode,
4:139
messageResponse);
4:140
else
4:141
Console.WriteLine(`The result of processing is unknown`);
4:142
}
4:143
4:144
Using the switch expression available since C# 8.0, the code can be even simpler!
4:145
static void Main()
4:146
{
4:147
var billingMode = GetBillingMode();
4:148
var messageResponse = ProcessCreditCardMethod();
4:149
CheckResult(messageResponse, billingMode);
4:150
}
4:151
private static CreditCardProcessingResult CheckResult(CreditCardProcessingResult messageResponse, BillingMode billingMode) => messageResponse switch
4:152
{
4:153
CreditCardProcessingResult.ResultA => CheckResultA(billingMode, messageResponse),
4:154
CreditCardProcessingResult.ResultB => CheckResultB(billingMode, messageResponse),
4:155
CreditCardProcessingResult.ResultC => CheckResultC(billingMode, messageResponse),
4:156
CreditCardProcessingResult.ResultD => CheckResultD(billingMode, messageResponse),
4:157
CreditCardProcessingResult.ResultE => CheckResultE(billingMode, messageResponse),
4:158
CreditCardProcessingResult.ResultF => CheckResultF(billingMode, messageResponse),
4:159
CreditCardProcessingResult.ResultG => CheckResultG(billingMode, messageResponse),
4:160
CreditCardProcessingResult.Succeed => CheckResultSucceed(billingMode, messageResponse),
4:161
_ => throw new ArgumentOutOfRangeException(nameof(messageResponse), $`Not expected value: {messageResponse}`),
4:162
};
4:163
4:164
The full code can be found in the GitHub repository of this chapter at https://github.com/PacktPublishing/Software-Architecture-with-C-Sharp-12-and-.NET-8-4E/tree/main/ch04 and demonstrates how lower-complexity code can be achieved. The following screenshot shows these results according to Code Metrics:
4:165
4:166
Figure 4.3: Cyclomatic complexity reduction after refactoring
4:167
As you can see in the preceding screenshot, there is a considerable reduction in complexity after refactoring. In Chapter 5, Implementing Code Reusability in C# 12, we will discuss the importance of refactoring for code reuse. The reason we are doing this here is the same – we want to eliminate duplication. It is important to remember that when you are refactoring code, you are writing it in a better way while respecting the input and output data that this code will process.
4:168
The key point here is that with the applied techniques, our understanding of the code increased and the complexity index decreased, thus proving the importance of cyclomatic complexity.
4:169
Depth of inheritance
4:170
This metric represents the number of classes inherited by the one that is being analyzed. The more classes you have inherited, the worse the metric will be. This is like class coupling and indicates how difficult it is to change the code of this class without impacting other ones, which neglects the Open/Close principle stated by SOLID. For instance, the following screenshot shows four inherited classes:
4:171
4:172
Figure 4.4: Depth of inheritance sample
4:173
You can see in the following screenshot that the deepest class has the worst metric, considering there are three other classes that can change its behavior:
4:174
4:175
Figure 4.5: Depth of inheritance metric
4:176
Inheritance is one of the basic object-oriented analysis principles. However, it can sometimes be bad for your code in that it can cause dependencies. So, if it makes sense to do so, consider using composition or aggregation instead of inheritance, as we will explain in the following section.
4:177
Class coupling
4:178
When you connect too many classes in a single class, obviously you will get tight coupling, and changing a participant causes unintended consequences in others. For sure, this can cause bad maintenance of your code, resulting in bugs that will make you spend more time trying to deliver a great solution. For instance, refer to Figure 4.6. It shows a design where aggregation has been performed a lot. There is no sense to the code itself:
4:179
4:180
Figure 4.6: Class coupling example
4:181
Once you have calculated the code metrics for the preceding design, you will see that the number of class coupling instances for the ProcessData() method, which calls ExecuteTypeA(), ExecuteTypeB(), and ExecuteTypeC(), equals three:
4:182
4:183
Figure 4.7: Class coupling metric
4:184
Microsoft suggests that the maximum number of class coupling instances should be nine, as presented at https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-class-coupling?view=vs-2022.
4:185
With composition/aggregation being a better practice than inheritance, and since you will decouple code written from your class, the use of interfaces will solve class coupling problems. For instance, the same code with the following design will give you a better result. Although the interface is not strictly required for this example, its usage enables us to evolve the solution for other execution types without impacting the classes already written, since you are not using inheritance to solve the problem.
4:186
4:187
Figure 4.8: Reducing class coupling
4:188
Note that using the interface in the design will allow you to increase the number of execution types without increasing the class coupling of the solution:
4:189
4:190
Figure 4.9: Class coupling results after applying aggregations
4:191
As a software architect, you must design your solution to have more cohesion than coupling. The literature indicates that good software has low coupling and high cohesion. In software development, high cohesion indicates that each class has its methods and data, with good relationships between them. Conversely, low coupling indicates that classes are not closely and directly connected. This is a basic principle that can guide you to a better architectural model.
4:192
Number of lines of code
4:193
This metric is useful in terms of making you understand the size of the code you are dealing with. There is no way to connect the number of lines of code and complexity, since the number of lines is not indicative of that. Conversely, the number of lines of code does show the software size and software design. For instance, if you have too many lines of code in a single class (more than 1,000 lines of code – 1 KLOC), this indicates that it is a bad design. Besides, if a class has too many methods, it obviously violates the Single Responsibility principle from SOLID.
4:194
In Visual Studio 2022, this metric was divided into lines of source code and lines of executable code. The first indicates the exact number of source lines, including blank lines. Conversely, the second one estimates the number of executable code lines.
4:195
As a software architect, you have the objective of delivering to your programmers a list of best practices that will enable each of them to improve their techniques for developing good software. Make sure they know the exact impacts of not achieving good metric results in their code. The metrics presented above are certainly a great way to start to achieve this objective. But let us see how using a version control system can be the difference between amateur and professional software development.
4:196
Using a version control system
4:197
You may find this topic a bit obvious, but many people and companies still do not regard a version control system as an essential tool for software development. A common reason why version control systems are not considered a priority, particularly in some situations, is the belief that they are unnecessary for solo coding projects or for study purposes. You may think that a version control system is only needed by teams inside companies. The purpose of addressing this is to force you to understand our point. There is no architectural model or best practice that can save software development if you do not use a version control system.
4:198
In the last few years, we have been enjoying the advantages of online version control systems, such as Azure DevOps, GitHub, and Bitbucket. The fact is, you must have a version control system in your software development life cycle, and there is no reason not to have one anymore, since most providers offer free versions for small groups. Even if you develop by yourself, these tools are useful for tracking your changes, managing your software versions, and guaranteeing the consistency and integrity of your code.
4:199
Dealing with version control systems in teams
4:200
The reason for using a version control system tool when you are alone is obvious. You want to keep your code safe. However, this kind of system was developed to solve team problems while writing code. For this reason, some features, such as branching and merging, were introduced to keep code integrity even in scenarios where the number of developers is quite large.
4:201
As a software architect, you will have to decide which branch strategy you will conduct in your team. Microsoft and GitHub suggest different ways to deliver that, and both are useful in some scenarios.
4:202
Information about how the Microsoft teams deal with DevOps can be found here: https://learn.microsoft.com/en-us/devops/develop/how-microsoft-develops-devops. The branching strategy presented in this article describes an approach where a branch is created for each release. They call it the release flow. The big difference here is that the master branch is not continuously deployed to production.
4:203
Conversely, GitHub describes its process at https://guides.github.com/introduction/flow/. This process is called GitHub flow and can be defined as a lightweight, branch-based workflow, where each development is created in a specific branch that will be reviewed by collaborators as soon as a pull request is created for feedback. As soon as the pull request is approved, the new code is merged to a master branch, so you can delete the development branch created before.
4:204
It is your choice; decide on the one that best fits your needs, but we do want you to understand that you need to have a strategy for controlling your code. In Chapter 8, Understanding DevOps Principles and CI/CD, we will discuss this in more detail. But now, let us see how to write safe code using C# so that you can develop a list of best practices to be shared with your developers.
4:205
Writing safe code in C#
4:206
C# can be considered a safe programming language by design. Unless you force it, there is no need for pointers, and memory release is, in most cases, managed by the garbage collector. Even so, some care should be taken so that you can get better and safer results from your code. Let us have a look at some common practices to ensure safe code in C#.
4:207
try-catch
4:208
Exceptions in coding are so frequent that you should have a way to manage them whenever they happen. try-catch statements are built to manage exceptions, and they are important for keeping your code safe. Be careful when they happen, since they can cause performance issues, as we discussed in Chapter 2, Non-Functional Requirements.
4:209
There are a lot of cases where an application crashes, and the reason for that is the lack of using try-catch. The following code shows an example of the lack of usage of the try-catch statement. It is worth mentioning that this is just an example of understanding the concept of an exception thrown without correct treatment. Consider using int.TryParse(textToConvert, out int result) to handle cases where a parse is unsuccessful:
4:210
private static int CodeWithNoTryCatch(string textToConvert)
4:211
{
4:212
return Convert.ToInt32(textToConvert);
4:213
}
4:214
4:215
Conversely, bad try-catch usage can cause damage to your code too, especially because you will not see the correct behavior of that code and may misunderstand the results provided.
4:216
The following code shows an example of an empty try-catch statement:
4:217
private static int CodeWithEmptyTryCatch(string textToConvert)
4:218
{
4:219
try
4:220
{
4:221
return Convert.ToInt32(textToConvert);
4:222
}
4:223
catch
4:224
{
4:225
return default;
4:226
}
4:227
}
4:228
4:229
try-catch statements must be connected to logging solutions so that you can have a response from the system that will indicate the correct behavior and, at the same time, not cause application crashes. The following code shows an ideal try-catch statement with logging management. It is worth mentioning that specific exceptions should be caught whenever possible, since catching a general exception will hide unexpected exceptions:
4:230
private static int CodeWithCorrectTryCatch(string textToConvert)
4:231
{
4:232
try
4:233
{