How to Make the Code Hard to Misuse?
With C# examples.
Code that a developer writes will be reused by that developer sometimes later or by other developers. Code reuse is something that is used regularly — new functionality is developed on top of existing reusable components.
When you introduce new code, you have a great opportunity to try to make life a lot easier for everyone (including you in the future) who will reuse your code — you can write your code in such a way that it’s hard to misuse it! As a result, new functionality can be developed faster and contain fewer bugs.
Here is a list of ideas with examples of how to make the code hard to misuse:
Use immutable data types so that client code can’t cause side effects
Mutable data types are fairly easy to misuse. A simple modification to, for example, a property of an object can cause side effects if the object is used elsewhere.
public class Person
{
public Person(Address address)
{
Address = address;
}
public Address Address { get; }
}
public class Address
{
public Address(string city, string zipCode)
{
City = city;
ZipCode = zipCode;
}
public string City { get; set; }
public string ZipCode { get; set; }
}