When you do some programming in C# with dot.Net, you can put all code in one file. However, after a while it becomes very difficult to maintain, like adding new functionality of for fixing bugs. There are some practices you can use to create software that will be easier to work with for you, and for others working on your code too.
The basic idea is Object Oriented Programming. Your code can represent an object from the real world, captured in a class that contains properties and functionality.
E.g. if you want to write a music player, your class can be named ‘Musicplayer’, that contains methods like ‘Play’, ‘Stop’, ‘Load’ or ‘Unload’. However, You need a windows program with buttons to start or stop as a user-interface; the ‘Musicplayer’-class itself is a passive thing. In the user interface you connect the click on the start button to the ‘Play’ method of the ‘Musicplayer’-player.
Some recommended practices
- Single Responsibility Principle – Create a structure with worker classes with one purpose, like clerks in an office that can handle only one detail of the work process.
- Separation of Concerns – separate your code in namespaces and modules, like departments in a company
- DRY (do not repeat yourself) – I repeat, prevent duplicate code.
Connect classes with interfaces, in stead of calling them directly. An interface is like a contract that describes how to cooperate.
Compare it like two parts of a device, that is connected with point-to-point wiring. If you rewire the devices and use a connector, it becomes much easier to maintain.
For instance, you can replace one part with an improved version, as long as it uses the same connector. You can also test the devices separately, as long as the same cable is used.
When writing code, similar benefits occur when you are using an interface to connect classes.
It takes a little overhead, by creating and implementing an interface, but at the long run it will be much easier to maintain.
In case of the musicplayer, you can write or extract an interface with the help of Visual Studio. Right click on the class name:
Select Quick Actions, the option “Extract interface…” appears:
A popup is opened, you can select the methods you want, and the name of the interface file:
It will generate an interface file like this:
Next you must let the MusicPlayer implement the Interface.
Finally, you can let your application use the MusicPlayer by using the IMusicPlayer-interface:
When you have another codebase to play audio, you can build a new player based on the same Interface and implement it:
This might seem silly, but consider you can select which player you can use in your code. That might be the case if you want your app to be compatible with systems that needs a different approach, like ASIO-support or an ancient OS. You can build a test like ‘isAsioEnabled’ and depending on the outcome use the Asio-player or the defaultplayer.