
在软件开发中,我们经常发现自己在兼顾两个看似矛盾的需求:以对人类思维有意义的方式组织代码,以及在运行时有效地处理代码。本文探讨了分层结构及其扁平化结构如何服务于不同的目的,以及理解这种二元性如何使我们成为更好的开发人员。
当我们开发软件时,我们在两个不同的环境中操作:
这些环境有不同的要求,在一种情况下效果最好的方法可能对另一种情况却不是最佳的。让我们来探究一下原因。
层次结构是人类认知的自然现象。我们本能地将信息组织在树和嵌套类别中。在软件开发中,这体现在几个方面:
考虑一个典型的 react 应用程序的路由结构:
src/
routes/
public/
homeroute.js
aboutroute.js
private/
dashboardroute.js
profileroute.js
common/
notfoundroute.js
此层次结构立即进行通信:
虽然层次结构非常适合组织,但在运行时处理方面,扁平结构通常会提供显着的优势:
让我们看一下该原则的实际应用示例。这是一个弥合分层路由组织和运行时处理之间差距的实用程序:
import { readdirsync, statsync } from 'fs';
import { join } from 'path';
export const deepmaproutes = async (routesdir) => {
const routes = [];
const traversedir = async (currentdir) => {
const files = readdirsync(currentdir);
for (const file of files) {
const filepath = join(currentdir, file);
const stat = statsync(filepath);
if (stat.isdirectory()) {
await traversedir(filepath);
} else if (
stat.isfile() &&
(file.endswith('.jsx') || file.endswith('.js')) &&
!file.startswith('index')
) {
const module = await import(filepath);
if (array.isarray(module.default)) {
routes.push(...module.default);
} else if (module.default) {
routes.push(module.default);
}
}
}
};
await traversedir(routesdir);
return routes;
};
这段代码将我们组织良好的分层路由结构转换为一个非常适合运行时处理的平面数组。好处包括:
这种具有运行时扁平化的分层组织原则适用于许多其他场景:
// hierarchical for organization
documents/
work/
projects/
personal/
finances/
// flattened for processing
[
'documents/work/projects/project1.doc',
'documents/personal/finances/budget.xlsx'
]
// hierarchical for ui
menu/
file/
new/
open/
edit/
copy/
paste/
// flattened for command processing
[
{ id: 'new', shortcut: 'ctrl+n' },
{ id: 'open', shortcut: 'ctrl+o' },
{ id: 'copy', shortcut: 'ctrl+c' }
]
// Hierarchical for documentation
components/
inputs/
text/
select/
displays/
card/
modal/
// Flattened for registration
{
'TextInput': TextInputComponent,
'SelectInput': SelectInputComponent,
'Card': CardComponent,
'Modal': ModalComponent
}
实现此模式时,请考虑以下准则:
保持真相来源的分层:以对开发人员有意义的分层结构维护您的主要组织。
运行时展平:创建在初始化或构建期间运行的展平实用程序。
维护元数据:展平时,如果需要,将重要的分层信息保留为元数据。
缓存扁平化结果:如果扁平化的计算成本很高,则缓存结果。
考虑可逆性:在某些情况下,您可能需要重建层次结构,因此维护必要的信息。
使用分层结构和扁平化结构的能力是开发人员武器库中的强大工具。虽然层次结构可以帮助我们组织和理解代码,但扁平结构通常提供在运行时处理代码的最有效方法。
记住:
这种查看和操作数据结构的认知灵活性可以带来更干净、更易于维护且更高效的代码。
您是否遇到过证明此模式有用的其他场景?在下面的评论中分享您的经验!
以上就是层次扁平化:管理软件设计复杂性的秘诀的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号