
solid 原则构成了干净、可扩展和可维护的软件开发的基础。尽管这些原则起源于面向对象编程 (oop),但它们可以有效地应用于 javascript (js) 和 typescript (ts) 框架,例如 react 和 angular。本文通过 js 和 ts 中的实际示例解释了每个原理。
原则:一个类或模块应该只有一个改变的理由。它应该负责单一功能。
在 react 中,我们经常看到组件负责太多事情——例如管理 ui 和业务逻辑。
反模式:
function userprofile({ userid }) {
const [user, setuser] = usestate(null);
useeffect(() => {
fetchuserdata();
}, [userid]);
async function fetchuserdata() {
const response = await fetch(`/api/users/${userid}`);
const data = await response.json();
setuser(data);
}
return <div>{user?.name}</div>;
}
此处,userprofile 组件违反了 srp,因为它同时处理 ui 渲染和数据获取。
立即学习“Java免费学习笔记(深入)”;
重构:
Zend框架2是一个开源框架,使用PHP 5.3 +开发web应用程序和服务。Zend框架2使用100%面向对象代码和利用大多数PHP 5.3的新特性,即名称空间、延迟静态绑定,lambda函数和闭包。 Zend框架2的组成结构是独一无二的;每个组件被设计与其他部件数的依赖关系。 ZF2遵循SOLID面向对象的设计原则。 这样的松耦合结构可以让开发人员使用他们想要的任何部件。我们称之为“松耦合”
344
// custom hook for fetching user data
function useuserdata(userid) {
const [user, setuser] = usestate(null);
useeffect(() => {
async function fetchuserdata() {
const response = await fetch(`/api/users/${userid}`);
const data = await response.json();
setuser(data);
}
fetchuserdata();
}, [userid]);
return user;
}
// ui component
function userprofile({ userid }) {
const user = useuserdata(userid); // moved data fetching logic to a hook
return <div>{user?.name}</div>;
}
通过使用自定义钩子 (useuserdata),我们将数据获取逻辑与ui分离,让每个部分负责单个任务。
在 angular 中,服务和组件可能因多重职责而变得混乱。
反模式:
@injectable()
export class userservice {
constructor(private http: httpclient) {}
getuser(userid: string) {
return this.http.get(`/api/users/${userid}`);
}
updateuserprofile(userid: string, data: any) {
// updating the profile and handling notifications
return this.http.put(`/api/users/${userid}`, data).subscribe(() => {
console.log('user updated');
alert('profile updated successfully');
});
}
}
此userservice 具有多种职责:获取、更新和处理通知。
重构:
@injectable()
export class userservice {
constructor(private http: httpclient) {}
getuser(userid: string) {
return this.http.get(`/api/users/${userid}`);
}
updateuserprofile(userid: string, data: any) {
return this.http.put(`/api/users/${userid}`, data);
}
}
// separate notification service
@injectable()
export class notificationservice {
notify(message: string) {
alert(message);
}
}
通过将通知处理拆分为单独的服务 (notificationservice),我们确保每个类都有单一职责。
原则:软件实体应该对扩展开放,对修改关闭。这意味着您应该能够扩展模块的行为而不更改其源代码。
您可能有一个运行良好的表单验证功能,但将来可能需要额外的验证逻辑。
反模式:
function validate(input) {
if (input.length < 5) {
return 'input is too short';
}
if (!input.includes('@')) {
return 'invalid email';
}
return 'valid input';
}
每当您需要新的验证规则时,您都必须修改此函数,这违反了 ocp。
重构:
function validate(input, rules) {
return rules.map(rule => rule(input)).find(result => result !== 'valid') || 'valid input';
}
const lengthrule = input => input.length >= 5 ? 'valid' : 'input is too short';
const emailrule = input => input.includes('@') ? 'valid' : 'invalid email';
validate('test@domain.com', [lengthrule, emailrule]);
现在,我们可以在不修改原始验证函数的情况下扩展验证规则,遵守 ocp。
在 angular 中,服务和组件的设计应允许在不修改核心逻辑的情况下添加新功能。
反模式:
export class notificationservice {
send(type: 'email' | 'sms', message: string) {
if (type === 'email') {
// send email
} else if (type === 'sms') {
// send sms
}
}
}
此服务违反了 ocp,因为每次添加新的通知类型(例如推送通知)时都需要修改发送方法。
重构:
interface notification {
send(message: string): void;
}
@injectable()
export class emailnotification implements notification {
send(message: string) {
// send email logic
}
}
@injectable()
export class smsnotification implements notification {
send(message: string) {
// send sms logic
}
}
@injectable()
export class notificationservice {
constructor(private notifications: notification[]) {}
notify(message: string) {
this.notifications.foreach(n => n.send(message));
}
}
现在,添加新的通知类型只需要创建新的类,而无需更改notificationservice本身。
原则:子类型必须可以替换其基本类型。派生类或组件应该能够替换基类而不影响程序的正确性。
当使用高阶组件 (hoc) 或有条件地渲染不同组件时,lsp 有助于确保所有组件的行为可预测。
反模式:
function button({ onclick }) {
return <button onclick={onclick}>click me</button>;
}
function linkbutton({ href }) {
return <a href={href}>click me</a>;
}
<button onclick={() => {}} />;
<linkbutton href="/home" />;
这里,button 和 linkbutton 不一致。一个用onclick,一个用href,替换起来很困难。
重构:
function clickable({ children, onclick }) {
return <div onclick={onclick}>{children}</div>;
}
function button({ onclick }) {
return <clickable onclick={onclick}>
<button>click me</button>
</clickable>;
}
function linkbutton({ href }) {
return <clickable onclick={() => window.location.href = href}>
<a href={href}>click me</a>
</clickable>;
}
现在,button 和 linkbutton 的行为类似,都遵循 lsp。
反模式:
class rectangle {
constructor(protected width: number, protected height: number) {}
area() {
return this.width * this.height;
}
}
class square extends rectangle {
constructor(size: number) {
super(size, size);
}
setwidth(width: number) {
this.width = width;
this.height = width; // breaks lsp
}
}
修改 square 中的 setwidth 违反了 lsp,因为 square 的行为与 rectangle 不同。
重构:
class shape {
area(): number {
throw new error('method not implemented');
}
}
class rectangle extends shape {
constructor(private width: number, private height: number) {
super();
}
area() {
return this.width * this.height;
}
}
class square extends shape {
constructor(private size: number) {
super();
}
area() {
return this.size * this.size;
}
}
现在,可以在不违反 lsp 的情况下替换 square 和 rectangle。
原则:客户端不应该被迫依赖他们不使用的接口。
react 组件有时会收到不必要的 props,导致紧密耦合和庞大的代码。
反模式:
function multipurposecomponent({ user, posts, comments }) {
return (
<div>
<userprofile user={user} />
<userposts posts={posts} />
<usercomments comments={comments} />
</div>
);
}
这里,组件依赖于多个 props,即使它可能并不总是使用它们。
重构:
function userprofilecomponent({ user }) {
return <userprofile user={user} />;
}
function userpostscomponent({ posts }) {
return <userposts posts={posts} />;
}
function usercommentscomponent({ comments }) {
return <usercomments comments={comments} />;
}
通过将组件拆分为更小的组件,每个组件仅取决于它实际使用的数据。
反模式:
interface worker {
work(): void;
eat(): void;
}
class humanworker implements worker {
work() {
console.log('working');
}
eat() {
console.log('eating');
}
}
class robotworker implements worker {
work() {
console.log('working');
}
eat() {
throw new error('robots do not eat'); // violates isp
}
}
在这里,robotworker 被迫实现一个不相关的 eat 方法。
重构:
interface worker {
work(): void;
}
interface eater {
eat(): void;
}
class humanworker implements worker, eater {
work() {
console.log('working');
}
eat() {
console.log('eating');
}
}
class robotworker implements worker {
work() {
console.log('working');
}
}
通过分离 worker 和 eater 接口,我们确保客户只依赖他们需要的东西。
原则:高层模块不应该依赖于低层模块。两者都应该依赖于抽象(例如接口)。
反模式:
function fetchuser(userid) {
return fetch(`/api/users/${userid}`).then(res => res.json());
}
function usercomponent({ userid }) {
const [user, setuser] = usestate(null);
useeffect(() => {
fetchuser(userid).then(setuser);
}, [userid]);
return <div>{user?.name}</div>;
}
这里,usercomponent 与 fetchuser 函数紧密耦合。
重构:
function usercomponent({ userid, fetchuserdata }) {
const [user, setuser] = usestate(null);
useeffect(() => {
fetchuserdata(userid).then(setuser);
}, [userid, fetchuserdata]);
return <div>{user?.name}</div>;
}
// usage
<usercomponent userid={1} fetchuserdata={fetchuser} />;
通过将 fetchuserdata 注入到组件中,我们可以轻松地更换测试或不同用例的实现。
反模式:
@injectable()
export class userservice {
constructor(private http: httpclient) {}
getuser(userid: string) {
return this.http.get(`/api/users/${userid}`);
}
}
@injectable()
export class usercomponent {
constructor(private userservice: userservice) {}
loaduser(userid: string) {
this.userservice.getuser(userid).subscribe(user => console.log(user));
}
}
usercomponent 与 userservice 紧密耦合,很难替换 userservice。
重构:
interface UserService {
getUser(userId: string): Observable<User>;
}
@Injectable()
export class ApiUserService implements UserService {
constructor(private http: HttpClient) {}
getUser(userId: string) {
return this.http.get<User>(`/api/users/${userId}`);
}
}
@Injectable()
export class UserComponent {
constructor(private userService: UserService) {}
loadUser(userId: string) {
this.userService.getUser(userId).subscribe(user => console.log(user));
}
}
通过依赖接口(userservice),usercomponent 现在与 apiuserservice 的具体实现解耦。
无论您是使用 react 或 angular 等框架开发前端,还是使用 node.js 开发后端,solid 原则都可以作为指导,确保您的软件架构保持可靠。
要将这些原则完全融入您的项目中:
solid 原则对于确保代码干净、可维护和可扩展非常有效,即使在 react 和 angular 等 javascript 和 typescript 框架中也是如此。应用这些原则使开发人员能够编写灵活且可重用的代码,这些代码易于随着需求的发展而扩展和重构。通过遵循 solid,您可以使您的代码库变得强大并为未来的增长做好准备。
以上就是在 JavaScript 和 TypeScript 框架中应用 SOLID 原则的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号