Влияние проектирования программ
Введено
7:25
Создание классов
Вот студент, хранящийся как три отдельных переменных: имя, курс и оценка. Это работает. Теперь добавьте тысячу студентов. Вам понадобятся три тысячи переменных…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| modular/ˈmɒdjʊlə/ | Модульность |
Two neat designs can report different averages
- A fictional record contains scores 80, absent and 100. Treating absence as zero gives
(80 + 0 + 100) / 3 = 60; omitting the absent result gives(80 + 100) / 2 = 90. - Separate methods can calculate either result correctly. Organization does not choose the reporting policy: establish what absence means, who decides, and which denominator the report must show before using the result.


Баллы составляют 80, отсутствуют и 100. Согласно политике доступных баллов, каково среднее значение?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Сумма присутствующих баллов равна 180, количество присутствующих равно 2, следовательно, 180/2 = 90.
Turn a requirement into a contract
- Specify whether absence means an unattempted assessed task, a task not assigned, or data not yet entered. These cases need not share a rule; the fictional example demonstrates consequences and does not prescribe a school grading policy.
- State the accepted input, the treatment of missing values and the result. If the rule is “average available scores”, an all-missing record has no average; report that case explicitly instead of inventing zero or dividing by zero.
Separate responsibilities for checking
- A modular 模块化 design separates
readScores,averageAvailableandprintReport. The average method can be checked with known values without reading a file or capturing formatted output. - Separation helps when interfaces remain clear. A change to the meaning of absence can still require changes in calculation, reporting and checks; small methods and good names alone do not prevent those dependencies.
Check ordinary and boundary cases
- For the available-score policy, check [80, absent, 100] gives 90, a single 80 gives 80, and [absent, absent] produces the agreed “no result” outcome. Do not merely check that the program runs.
- The calculation below uses
nullfor missing values. It returns a double average and rejects the all-missing case. It assumes a non-null array of ordinary scores; input validation and reporting are separate responsibilities.
public class AverageAvailable {
public static double averageAvailable(Integer[] scores) {
double total = 0;
int present = 0;
for (Integer score : scores) {
if (score != null) {
total += score;
present++;
}
}
if (present == 0) {
throw new IllegalArgumentException("No available scores");
}
return total / present;
}
}
Модульный дизайн (независимые, хорошо названные части) прежде всего упрощает...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Модульность делает изменения безопаснее, а части — повторно используемыми.
При повторном использовании одного метода несколькими вызывателями исправление этого_methoda может принести пользу всем вызывателям без редактирования дублированных копий.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Верно: вызыватели повторно используют реализацию. Тем не менее, необходимо пересмотреть контракт метода и последствия изменений.
Смещение в данных или логике программы может приводить к несправедливым результатам на больших объемах.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Выборы в дизайне влияют на реальных людей — учитывайте, кто пострадает.
Для проверки вычисления среднего независимо от ввода и печатного вывода, какой дизайн лучше всего изолирует эту ответственность?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Разделение вычисления с вводом и выводом позволяет проводить проверки по известным баллам без выполнения этих других операций. Само по себе наличие небольших методов не гарантирует корректности.
Проектирование программ — это исключительно косметика и не влияет на безопасность изменений кода.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Дизайн определяет, насколько безопасно можно изменять программу.
Показанный метод averageAvailable возвращает ноль для массива, состоящего только из отсутствующих значений.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Неверно: он отвергает этот случай через IllegalArgumentException, поскольку отсутствие доступных баллов не определяет среднее значение.
Report consequences to affected users
- A report of 90 should state that it averages two available scores out of three records, with one absent result omitted. Reporting only 90 hides information a reader needs to compare outcomes.
- Review who may be affected by the data and policy. A consistent calculation may still treat different kinds of absence inappropriately; test the agreed requirements and make the outcome understandable to users.
Modularity makes a policy easier to inspect and test; it does not make that policy fair or appropriate. The averages 60 and 90 use different denominators. Choose and disclose the rule rather than silently selecting whichever result looks better.
Хорошее или плохое проектирование?
Выборы в проектировании имеют реальные последствия. Распределите каждый исход.
Carry a policy change across the design
- If the authorized requirement changes to count an unattempted task as zero, update the denominator, relevant examples, checks and report wording. Reusing a method is useful only when its contract matches the new task.
- Review testability, correctness and user understanding separately. Clear boundaries reduce some change risks, but callers and shared assumptions must still be checked when a method's contract changes.
Program design affects maintainability and people. Separate responsibilities so behavior can be checked, define the missing-data policy, test its boundary cases and disclose the denominator. Correct arithmetic and neat structure do not establish an appropriate policy by themselves.
Match the change to the issue it addresses.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
A modular structure enables checking but cannot choose the right policy by itself.
Что пошло не так? Это увидит только команда сайта.