Читаем Thinking In C++. Volume 2: Practical Programming полностью

What should you do when clients fail to give you valid input? They have broken the contract, and you need to let them know. As we mentioned earlier, this is not the best time to abort the program (although you’re justified in doing so since the contract was violated), but an exception is certainly in order. This is why the Standard C++ library throws exceptions derived from logic_error, such as out_of_range.[16] If there are functions that only you call, however, such as private functions in a class of your own design, the assert( ) macro is appropriate, since you have total control over the situation and you certainly want to debug your code before shipping.

Since post-conditions are totally your responsibility, you might think assertions also apply, and you would be partially right. It is appropriate to use an assertion for any invariant at any time, including when a function has finished its work. This especially applies to class member functions that maintain the state of an object. In the MyVector example earlier, for instance, a reasonable invariant for all public member functions would be

assert(0 <= nextSlot && nextSlot <= capacity);

or, if nextSlot is an unsigned integer, simply

assert(nextSlot <= capacity);

Such an invariant is called a class invariant and can reasonably be enforced by an assertion. Subclasses play the role of subcontractor to their base classes in that they must maintain the original contract the base class has with its clients. For this reason, the pre-conditions in derived classes must impose no extra requirements beyond those in the base contract, and the post-conditions must deliver at least as much.[17] 

Validating results returned to the client, however, is nothing more or less than testing, so using post-condition assertions in this case would be duplicating work. There’s nothing wrong with it; it’s just an exercise in redundancy. Yes, it’s good documentation, but more than one developer has been fooled into using post-condition assertions as a substitute for unit testing. Bad idea!.

<p>A simple unit test framework</p>

Writing software is all about meeting requirements.[18] It doesn’t take much experience, however, to figure out that coming up with requirements in the first place is no easy task, and, more important, requirements are not static. It’s not unheard of to discover at a weekly project meeting that what you just spent the week doing is not exactly what the users really want.

Frustrating? Yes. Reasonable? Also, yes! It is unreasonable to expect mere humans to be able to articulate software requirements in detail without sampling an evolving, working system. It's much better to specify a little, design a little, code a little, test a little. Then, after evaluating the outcome, do it all over again. The ability to develop from soup to nuts in such an iterative fashion is one of the great advances of this object-oriented era in software history. It requires nimble programmers who can craft resilient code. Change is hard.

Ironically, another impetus for change comes from you, the programmer. The craftsperson in you likely has the habit of continually improving the physical design of working code. What maintenance programmer hasn’t had occasion to curse the aging, flagship company product as a convoluted patchwork of spaghetti, wholly resistant to modification? Management’s knee-jerk reluctance to let you tamper with a functioning system, while not totally unfounded, robs code of the resilience it needs to endure. "If it’s not broken, don’t fix it" eventually gives way to, "We can’t fix it—rewrite it." Change is necessary.

Fortunately, our industry has finally gotten used to the discipline of refactoring, the art of internally restructuring code to improve its design, without changing the functionality visible to the user.[19] Such tweaks include extracting a new function from another, or its inverse, combining member functions; replacing a member function with an object; parameterizing a member function or class; and replacing conditionals with polymorphism. Refactoring helps code embrace evolution.

Whether the force for change comes from users or programmers, however, there is still the risk that changes today will break what worked yesterday. What is needed is a way to build code that withstands the winds of change and actually improves over time.

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных