Yesterday I’ve read 3 chapters of the “Code Complete“. First one of them was a “Classes” and second was “Methods”. I would say that I took almost nothing for myself from those pages, but the third one was “Defense Programming” and it was quite enjoyable to read.

Classes

Class should stand for one logical unit of understanding from real world or from your system. In other worlds it should be noun, that could do some appropriate operations. It is not just a set of data. Also class should have Single Responsibility – not doing things it should not do and not be cohesive to other classes. Class should not contain too much data and too many methods.
After that McConnel talks about the Composition and Inheritance.
Use inheritance when behavior contract is the same and data is the same to some extend, but only concrete behavior differs, but not expectations of it.
Use composition when behavior is 100% the same, but you still could distinguish what you have before and what you would like to have further.
This means that no need to have AccountLessPerson if the person does not have bank account, it definitely better to have Person with field BankAccount.
Liskov Substitution Principle says that once you have class B derived from class A, other classes should work with B by the contract which is the same as A declares, only enhancements to the behavior is allowed, no real change in it.

Methods

It was boring to read this chapter. i.e. methods should have appropriate names, they should not be longer than N lines of code and be readable, they should not take more than 7 parameters, they should not change params, they should not change global fields etc….
It had to be much better to read there more about how methods should interact with other system.

Defence Programming

This was the most interesting part for me. This all is about building the wall of protection to your system. And this is needed to serve two main purposes: first is stability of the system and the second is for insuring correct behavior.
Assert
Assertion is the way to defense your code from wrong input data, and even defensing yourself from giving wrong result. For example in the beginning of method GetOrdersForAccountNumber(int accountNumber) you could have Assert.That(accountNumber > 0, “since you will not be able to make order with wrong number”) and after you finished with all calculations you could have Assert.That(orders != null, “because don’t think that that is good idea to pass out null object…”).
Exception handling
Exceptions is the tool for working with unusual situations that occur in your application. Some languages still don’t have build-in exception handling, and I’m so lucky that I work with such language like C#. McConner says “Develop with language, not on language”, but the C# just leads to writing a good code. Exception handling is quite big theme to discuss so I hope to have separate post on it.