title
stringlengths
3
46
content
stringlengths
0
1.6k
4:234
return Convert.ToInt32(textToConvert);
4:235
}
4:236
catch (FormatException err)
4:237
{
4:238
Logger.GenerateLog(err);
4:239
return 0;
4:240
}
4:241
}
4:242
4:243
It is very important to note that exceptions are, computationally speaking, expensive. No matter whether you are throwing them to indicate an error or catching them to manage errors, it takes a lot of computational processing. So, it is common, and preferable, to rely on a higher-level exception handler instead of trying to handle everything everywhere, as the code might become hard to reason about, particularly if there is not a good action to take when an exception happens. That means you may not handle the exceptions in every method, especially if you do not know what to do with them at that part of the code and you will throw it again to a higher-level handle. You should prioritize handling exceptions where meaningful actions can be taken.
4:244
However, it is also worth mentioning that exception errors delivered to the end user can cause the feeling that bad software was delivered. As a software architect, you should conduct code inspections to define the best behavior for code. Instability in a system, like unexpected crashes and high-memory usage, is often connected to the lack of try-catch statements in code.
4:245
try-finally and using
4:246
Memory leaks can be considered one of the worst software behaviors. They cause instability, bad usage of computer resources, and undesired application crashes. C# tries to solve this with Garbage Collector, which automatically releases objects from memory as soon as it realizes an object can be freed. The trigger for Garbage Collector is well explained at https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals.
4:247
Objects that interact with I/O are the ones that generally are not managed by Garbage Collector: the filesystem, sockets, and so on. The following code is an example of the incorrect usage of a FileStream object because it thinks Garbage Collector will release the memory used, but it will not:
4:248
private static void CodeWithIncorrectFileStreamManagement()
4:249
{
4:250
FileStream file = new (`C:file.txt`, FileMode.CreateNew);
4:251
byte[] data = GetFileData();
4:252
file.Write(data, 0, data.Length);
4:253
}
4:254
4:255
Besides, it takes a while for Garbage Collector to interact with objects that need to be released, and sometimes, you may want to do it yourself. For both cases, the use of try-finally or using statements is the best practice:
4:256
private static void CorrectFileStreamManagementFirstOption()
4:257
{
4:258
FileStream file = new (`C:file.txt`,FileMode.CreateNew);
4:259
try
4:260
{
4:261
byte[] data = GetFileData();
4:262
file.Write(data, 0, data.Length);
4:263
}
4:264
finally
4:265
{
4:266
file.Dispose();
4:267
}
4:268
}
4:269
private static void CorrectFileStreamManagementSecondOption()
4:270
{
4:271
using (FileStream file = new (`C:file.txt`, FileMode.CreateNew))
4:272
{
4:273
byte[] data = GetFileData();
4:274
file.Write(data, 0, data.Length);
4:275
}
4:276
}
4:277
private static void CorrectFileStreamManagementThirdOption()
4:278
{
4:279
using FileStream file = new (`C:file.txt`, FileMode.CreateNew);
4:280
byte[] data = GetFileData();
4:281
file.Write(data, 0, data.Length);
4:282
}
4:283
4:284
The preceding code shows exactly how to deal with objects that are not managed by Garbage Collector. Both try-finally and using are implemented. As a software architect, you do need to pay attention to this kind of code. The lack of try-finally or using statements can cause huge damage to software behavior when it is running. It is worth mentioning that using code analysis tools, such as Sonar Lint and Code Analysis, will automatically alert you to these sorts of problems.
4:285
The IDisposable interface
4:286
In the same way that you will have trouble if you do not manage objects created inside a method with try-finally/using statements, objects created in a class that does not properly implement the IDisposable interface may cause memory leaks in your application. For this reason, when you have a class that deals with and creates objects, you should implement the Disposable pattern to guarantee the release of all resources created by the class:
4:287
4:288
Figure 4.10: IDisposable interface implementation
4:289
The good news is that Visual Studio gives you a code snippet to implement this interface by simply indicating it in your code, and then you right-click on the Quick Actions and Refactoring options, as you can see in the preceding screenshot.
4:290
Once you have inserted the code, you need to follow the to-do instructions so that you have the correct pattern implemented.
4:291
As a software architect, you will be responsible not only for the architecture defined in a system but also for how this system performs in operation. Memory leaks and bad performance, in general, are caused by errors related to the try-catch strategy, a lack of try-finally/using, and wrong or no implementation of IDisposable. So be sure that your team knows how to deal with these techniques.
4:292
4:293
Since we have covered some important information about how to write safe code in C#, it would be nice to get some tips and tricks for coding in this programming language. Let us do so in the next topic of this chapter.
4:294
4:295
.NET 8 tips and tricks for coding
4:296
.NET 8 implements some good features that help us to write better code. One of the most useful things for having cleaner code is dependency injection (DI), which will be discussed in Chapter 6, Design Patterns and .NET 8 Implementation. There are some good reasons for considering this. The first one is that you will only need to worry about disposing of the injected objects if you are the creator of them.
4:297
Besides, DI enables you to inject ILogger, a useful tool for debugging exceptions that will need to be managed by try-catch statements in your code. Furthermore, programming in C# with .NET 8 must follow the common good practices of any programming language. The following list shows some of these:
4:298
4:299
Classes, methods, and variables should have understandable names: The name should explain everything that the reader needs to know. There should be no need for an explanatory comment unless these declarations are public.
4:300
Methods should not have high complexity levels: Cyclomatic complexity should be checked so that methods do not have too many lines of code.
4:301
Members must have the correct visibility: As an object-oriented programming language, C# enables encapsulation with different visibility keywords. C# 9 has presented init-only setters, so you can create init property/index accessors instead of set, defining these members as read-only following the construction of the object.
4:302
Duplicate code should be avoided: There is no reason for having duplicate code in a high-level programming language such as C#.
4:303
Objects should be checked before usage: Since null objects can exist, code must have null type checking. It is worth mentioning that since C# 8, we have nullable reference types to avoid errors related to nullable objects. You can refer to https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references for more information about nullable reference types.
4:304
Constants and enumerators should be used: A good way of avoiding magic numbers and text inside code is to transform this information into constants and enumerators, which generally are more understandable.
4:305
Unsafe code should be avoided: Unsafe code enables you to deal with pointers in C#. Unless there is no other way to implement the solution, unsafe code should be avoided.
4:306
try-catch statements cannot be empty: There is rarely a reason to use a try-catch statement without treatment in the catch area. Moreover, the caught exceptions should be as specific as possible, and not just an “exception,” to avoid swallowing unexpected exceptions.
4:307
Dispose of the objects that you have created, if they are disposable: Even for objects where Garbage Collector will take care of the disposed-of object, consider disposing of objects that you were responsible for creating yourself.
4:308
At least public methods should be commented: Considering that public methods are the ones used outside your library, they must be explained for their correct external usage.
4:309
switch-case statements must have a default treatment: Since switch-case statements may receive an entrance variable unknown in some cases, the default treatment will guarantee that code will not break in such a situation.
4:310
4:311
As a software architect, you may consider a good practice of providing a code pattern for your developers that will be used to keep the style of code consistent as a team. You can also use this code pattern as a checklist for coding inspections, which will enrich software code quality.
4:312
Identifying well-written code
4:313
It is not easy to identify whether code is well written. The best practices described so far can certainly guide you as a software architect to define a standard for your team. However, even with a standard, mistakes will happen, and you will probably find them only after code is in production. The decision to refactor code in production just because it does not follow all the standards you define is not an easy one to take, especially if the code in question works properly. Some people conclude that well-written code is simply code that works well in production. However, this can surely cause damage to the software’s life since developers might be influenced by that non-standard code.
4:314
For this reason, as a software architect, you need to find ways to enforce adherence to the coding standard you’ve defined. Luckily, nowadays, we have many options for tools that can help us with this task. They are called static code analysis tools, and using them provides a great opportunity to improve both the software developed and the team’s programming knowledge.
4:315
The reason your developers will evolve with code analysis is that you start to disseminate knowledge between them during code inspections. The tools that we have now have the same purpose. Even better, with Roslyn, they do this task while you write the code. Roslyn is the compiler platform for .NET, and it enables you to develop some tools for analyzing code. These analyzers can check style, quality, design, and other issues.
4:316
For instance, look at the following code. It does not make any sense, but you can still see that there are some mistakes:
4:317
using System;
4:318
static void Main(string[] args)
4:319
{
4:320
try
4:321
{
4:322
int variableUnused = 10;
4:323
int variable = 10;
4:324
if (variable == 10)
4:325
{
4:326
Console.WriteLine(`variable equals 10`);
4:327
}
4:328
else
4:329
{
4:330
switch (variable)
4:331
{
4:332
case 0:
4:333
Console.WriteLine(`variable equals 0`);