برچسب: Things

  • 8 things about Records in C# you probably didn’t know | Code4IT

    8 things about Records in C# you probably didn’t know | Code4IT


    C# recently introduced Records, a new way of defining types. In this article, we will see 8 things you probably didn’t know about C# Records

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Records are the new data type introduced in 2021 with C# 9 and .NET Core 5.

    public record Person(string Name, int Id);
    

    Records are the third way of defining data types in C#; the other two are class and struct.

    Since they’re a quite new idea in .NET, we should spend some time experimenting with it and trying to understand its possibilities and functionalities.

    In this article, we will see 8 properties of Records that you should know before using it, to get the best out of this new data type.

    1- Records are immutable

    By default, Records are immutable. This means that, once you’ve created one instance, you cannot modify any of its fields:

    var me = new Person("Davide", 1);
    me.Name = "AnotherMe"; // won't compile!
    

    This operation is not legit.

    Even the compiler complains:

    Init-only property or indexer ‘Person.Name’ can only be assigned in an object initializer, or on ’this’ or ‘base’ in an instance constructor or an ‘init’ accessor.

    2- Records implement equality

    The other main property of Records is that they implement equality out-of-the-box.

    [Test]
    public void EquivalentInstances_AreEqual()
    {
        var me = new Person("Davide", 1);
        var anotherMe = new Person("Davide", 1);
    
        Assert.That(anotherMe, Is.EqualTo(me));
        Assert.That(me, Is.Not.SameAs(anotherMe));
    }
    

    As you can see, I’ve created two instances of Person with the same fields. They are considered equal, but they are not the same instance.

    3- Records can be cloned or updated using ‘with’

    Ok, so if we need to update the field of a Record, what can we do?

    We can use the with keyword:

    [Test]
    public void WithProperty_CreatesNewInstance()
    {
        var me = new Person("Davide", 1);
        var anotherMe = me with { Id = 2 };
    
        Assert.That(anotherMe, Is.Not.EqualTo(me));
        Assert.That(me, Is.Not.SameAs(anotherMe));
    }
    

    Take a look at me with { Id = 2 }: that operation creates a clone of me and updates the Id field.

    Of course, you can use with to create a new instance identical to the original one.

    [Test]
    public void With_CreatesNewInstance()
    {
        var me = new Person("Davide", 1);
    
        var anotherMe = me with { };
    
        Assert.That(anotherMe, Is.EqualTo(me));
        Assert.That(me, Is.Not.SameAs(anotherMe));
    }
    

    4- Records can be structs and classes

    Basically, Records act as Classes.

    public record Person(string Name, int Id);
    

    Sometimes that’s not what you want. Since C# 10 you can declare Records as Structs:

    public record struct Point(int X, int Y);
    

    Clearly, everything we’ve seen before is still valid.

    [Test]
    public void EquivalentStructsInstances_AreEqual()
    {
        var a = new Point(2, 1);
        var b = new Point(2, 1);
    
        Assert.That(b, Is.EqualTo(a));
        //Assert.That(a, Is.Not.SameAs(b));// does not compile!
    }
    

    Well, almost everything: you cannot use Is.SameAs() because, since structs are value types, two values will always be distinct values. You’ll get notified about it by the compiler, with an error that says:

    The SameAs constraint always fails on value types as the actual and the expected value cannot be the same reference

    5- Records are actually not immutable

    We’ve seen that you cannot update existing Records. Well, that’s not totally correct.

    That assertion is true in the case of “simple” Records like Person:

    public record Person(string Name, int Id);
    

    But things change when we use another way of defining Records:

    public record Pair
    {
        public Pair(string Key, string Value)
        {
            this.Key = Key;
            this.Value = Value;
        }
    
        public string Key { get; set; }
        public string Value { get; set; }
    }
    

    We can explicitly declare the properties of the Record to make it look more like plain classes.

    Using this approach, we still can use the auto-equality functionality of Records

    [Test]
    public void ComplexRecordsAreEquatable()
    {
        var a = new Pair("Capital", "Roma");
        var b = new Pair("Capital", "Roma");
    
        Assert.That(b, Is.EqualTo(a));
    }
    

    But we can update a single field without creating a brand new instance:

    [Test]
    public void ComplexRecordsAreNotImmutable()
    {
        var b = new Pair("Capital", "Roma");
        b.Value = "Torino";
    
        Assert.That(b.Value, Is.EqualTo("Torino"));
    }
    

    Also, only simple types are immutable, even with the basic Record definition.

    The ComplexPair type is a Record that accepts in the definition a list of strings.

    public record ComplexPair(string Key, string Value, List<string> Metadata);
    

    That list of strings is not immutable: you can add and remove items as you wish:

    [Test]
    public void ComplexRecordsAreNotImmutable2()
    {
        var b = new ComplexPair("Capital", "Roma", new List<string> { "City" });
        b.Metadata.Add("Another Value");
    
        Assert.That(b.Metadata.Count, Is.EqualTo(2));
    }
    

    In the example below, you can see that I added a new item to the Metadata list without creating a new object.

    6- Records can have subtypes

    A neat feature is that we can create a hierarchy of Records in a very simple manner.

    Do you remember the Person definition?

    public record Person(string Name, int Id);
    

    Well, you can define a subtype just as you would do with plain classes:

    public record Employee(string Name, int Id, string Role) : Person(Name, Id);
    

    Of course, all the rules of Boxing and Unboxing are still valid.

    [Test]
    public void Records_CanHaveSubtypes()
    {
        Person meEmp = new Employee("Davide", 1, "Chief");
    
        Assert.That(meEmp, Is.AssignableTo<Employee>());
        Assert.That(meEmp, Is.AssignableTo<Person>());
    }
    

    7- Records can be abstract

    …and yes, we can have Abstract Records!

    public abstract record Box(int Volume, string Material);
    

    This means that we cannot instantiate new Records whose type is marked ad Abstract.

    var box = new Box(2, "Glass"); // cannot create it, it's abstract
    

    On the contrary, we need to create concrete types to instantiate new objects:

    public record PlasticBox(int Volume) : Box(Volume, "Plastic");
    

    Again, all the rules we already know are still valid.

    [Test]
    public void Records_CanBeAbstract()
    {
        var plasticBox = new PlasticBox(2);
    
        Assert.That(plasticBox, Is.AssignableTo<Box>());
        Assert.That(plasticBox, Is.AssignableTo<PlasticBox>());
    }
    

    8- Record can be sealed

    Finally, Records can be marked as Sealed.

    public sealed record Point3D(int X, int Y, int Z);
    

    Marking a Record as Sealed means that we cannot declare subtypes.

    public record ColoredPoint3D(int X, int Y, int Z, string RgbColor) : Point3D(X, Y, X); // Will not compile!
    

    This can be useful when exposing your types to external systems.

    This article first appeared on Code4IT

    Additional resources

    As usual, a few links you might want to read to learn more about Records in C#.

    The first one is a tutorial from the Microsoft website that teaches you the basics of Records:

    🔗 Create record types | Microsoft Docs

    The second one is a splendid article by Gary Woodfine where he explores the internals of C# Records, and more:

    🔗C# Records – The good, bad & ugly | Gary Woodfine.

    Finally, if you’re interested in trivia about C# stuff we use but we rarely explore, here’s an article I wrote a while ago about GUIDs in C# – you’ll find some neat stuff in there!

    🔗5 things you didn’t know about Guid in C# | Code4IT

    Wrapping up

    In this article, we’ve seen 8 things you probably didn’t know about Records in C#.

    Records are quite new in the .NET ecosystem, so we can expect more updates and functionalities.

    Is there anything else we should add? Or maybe something you did not expect?

    Happy coding!

    🐧



    Source link

  • measuring things to ensure prosperity &vert; Code4IT

    measuring things to ensure prosperity | Code4IT


    Non-functional requirements matter, but we often forget to validate them. You can measure them by setting up Fitness Functions.

    Table of Contents

    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Just creating an architecture is not enough; you should also make sure that the pieces of stuff you are building are, in the end, the once needed by your system.

    Is your system fast enough? Is it passing all the security checks? What about testability, maintainability, and other -ilities?

    Fitness Functions are components of the architecture that do not execute functional operations, but, using a set of tests and measurements, allow you to validate that the system respects all the non-functional requirements defined upfront.

    Fitness Functions: because non-functional requirements matter

    An architecture is made of two main categories of requirements: functional requirements and non-functional requirements.

    Functional requirements are the most easy to define and to test: if one of the requirements is “a user with role Admin must be able to see all data”, then writing a suite of tests for this specific requirement is pretty straightforward.

    Non-functional requirements are, for sure, as important as functional requirements, but are often overlooked or not detailed. “The system must be fast”: ok, how fast? What do you mean with “fast”? What is an acceptable value of “fast”?

    If we don’t have a clear understanding of non-functional requirements, then it’s impossible to measure them.

    And once we have defined a way to measure them, how can we ensure that we are meeting our expectations? Here’s where Fitness Functions come in handy.

    In fact, Fitness Functions are specific components that focus on non-functional requirements, executing some calculations and providing metrics that help architects and developers ensure that the system’s architecture aligns with business goals, technical requirements, and other quality attributes.

    Why Fitness Functions are crucial for future-proof architectures

    When creating an architecture, you must think of the most important -ilities for that specific case. How can you ensure that the technical choices we made meet the expectations?

    By being related to specific and measurable metrics, Fitness Functions provide a way to assess the architecture’s quality and performance, reducing the reliance on subjective opinions by using objective measurements. A metric can be a simple number (e.g., “maximum number of requests per second”), a percentage value (like “percentage of code covered by tests”) or other values that are still measurable.

    Knowing how the system behaves in regards to these measures allows architects to work on the continuous improvement of the system: teams can identify areas for improvement and make decisions based not on personal opinion but on actual data to enhance the system.

    Having a centralized place to view the historical values of a measure helps understanding if you have done progresses or, as time goes by, the quality has degraded.

    Still talking about the historical values of the measures, having a clear understanding of what is the current status of such metrics can help in identifying potential issues early in the development process, allowing teams to address them before they become critical problems.

    For example, by using Fitness Functions, you can ensure that the system is able to handle a certain amount of users per second: having proper measurements, you can identify which functionalities are less performant and, in case of high traffic, may bring the whole system down.

    You are already using Fitness Functions, but you didn’t know

    Fitness Functions sound like complex things to handle.

    Even though you can create your own functions, most probably you are already using them without knowing it. Lots of tools are available out there that cover several metrics, and I’m sure you’ve already used some of them (or, at least, you’ve already heard of them).

    Tools like SonarQube and NDepend use Fitness Functions to evaluate code quality based on metrics such as code complexity, duplication, and adherence to coding standards. Those metrics are calculated based on static analysis of the code, and teams can define thresholds under which a system can be at risk of losing maintainability. An example of metric related to code quality is Code Coverage: the higher, the better (even though 100% of code coverage does not guarantee your code is healthy).

    Tools like JMeter or K6 help you measure system performance under various conditions: having a history of load testing results can help ensure that, as you add new functionalities to the system, the performance on some specific modules does not downgrade.

    All in all, most of the Fitness Functions can be set to be part of CI/CD pipelines: for example, you can configure a CD pipeline to block the deployment of the code on a specific system if the load testing results of the new code are worse than the previous version. Or you could block a Pull Request if the code coverage percentage is getting lower.

    Further readings

    A good way to start experimenting with Load Testing is by running them locally. A nice open-source project is K6: you can install it on your local machine, define the load phases, and analyze the final result.

    🔗 Getting started with Load testing with K6 on Windows 11 | Code4IT

    This article first appeared on Code4IT 🐧

    But, even if you don’t really care about load testing (maybe because your system is not expected to handle lots of users), I’m sure you still care about code quality and their tests. When using .NET, you can collect code coverage reports using Cobertura. Then, if you are using Azure DevOps, you may want to stop a Pull Request if the code coverage percentage has decreased.

    Here’s how to do all of this:

    🔗 Cobertura, YAML, and Code Coverage Protector: how to view Code Coverage report on Azure DevOps | Code4IT

    Wrapping up

    Sometimes, there are things that we use every day, but we don’t know how to name them: Fitness Functions are one of them – and they are the foundation of future-proof software systems.

    You can create your own Fitness Functions based on whatever you can (and need to) measure: from average page loading to star-rated customer satisfaction. In conjunction with a clear dashboard, you can provide a clear view of the history of such metrics.

    I hope you enjoyed this article! Let’s keep in touch on LinkedIn, Twitter or BlueSky! 🤜🤛

    Happy coding!

    🐧





    Source link

  • 3 Things to Know Before Launching Your Basement Renovation Business


    Launching a basement renovation business can be an exciting yet challenging venture. The growing home improvement industry offers numerous opportunities, but success requires a sound understanding of key factors that can impact your business. By focusing on areas like moisture management, energy efficiency, and financial safeguards against fraud, you can build a robust foundation for your business and ensure long-term profitability.

    Managing Moisture and Mold

    Basements, by their very nature, are prone to moisture issues which can prove detrimental if not addressed properly. Mold begins to grow on damp surfaces quickly, potentially within 24 to 48 hours, making it imperative for business owners to incorporate effective waterproofing solutions. Implementing moisture management strategies, such as proper sealing and ventilation, ensures a healthier indoor environment for clients and protects the integrity of the renovation work.

    Understanding the importance of moisture control can also enhance the reputation of your business. Clients are likely to choose a contractor who prioritizes their long-term comfort and safety in the space. By offering preventative solutions and educating clients about ongoing maintenance, you position your business as a trusted resource in basement renovations.

    Moreover, addressing moisture-related issues upfront can lead to cost savings in the long run. Tackling potential problems before they escalate reduces the risk of adverse effects on construction materials and additional expenses. Such proactive measures not only protect your business from unexpected costs but also boost client satisfaction and referrals.

    Achieving Energy Efficiency

    Energy efficiency is increasingly becoming a priority for homeowners, and your basement renovation business should reflect this trend. Modernizing basements with energy-efficient features brings immediate and long-term benefits to clients. For instance, using LED lights in renovation projects is not only appealing but also practical, as they consume up to 80% less energy than traditional incandescent lighting.

    By integrating energy-saving measures, your business can set itself apart in a competitive market. Offering solutions such as enhanced insulation, efficient HVAC systems, and smart home technology cultivates a reputation for innovation and environmental responsibility. These improvements not only enhance the comfort of the renovated space but also help reduce energy bills for clients over time.

    Furthermore, aligning your renovation services with green building standards opens the door to new clientele interested in sustainable living. As awareness around environmental impact grows, businesses that adapt accordingly find they can attract a diverse client base. Demonstrating a commitment to sustainability not only establishes credibility but can also tap into emerging market demands.

    Safeguarding Against Fraud

    While the prospect of fraud may not be immediately apparent, it is a significant concern for any business, including basement renovation operations. Statistics reveal that businesses lose approximately 5% of their revenue each year to fraudulent activities. Cultivating a secure business strategy is essential to minimizing these risks and protecting your financial interests.

    One effective method of reducing fraud is implementing robust financial controls. Monitoring cash flows, conducting regular audits, and separating financial duties among employees can diminish the potential for deceptive activities. By maintaining stringent internal processes, you help preserve the integrity and reputation of your business.

    Additionally, investing in employee training to recognize and report suspicious behavior empowers your team to act proactively. An informed workforce is one of your greatest defenses against fraud, ensuring you can focus on serving clients and developing your business. By prioritizing security measures, you contribute to both your enterprise’s health and clients’ peace of mind.

    Launching a basement renovation business is a rewarding endeavor, especially when armed with the knowledge of pivotal factors impacting success. Addressing moisture and mold issues, prioritizing energy efficiency, and securing operations against fraud are essential components. By integrating these elements, you create a dynamic and resilient business model poised for growth and longevity.



    Source link