在 JavaScript 和 TypeScript 框架中应用 SOLID 原则

在 javascript 和 typescript 框架中应用 solid 原则

简介

solid 原则构成了干净、可扩展和可维护的软件开发的基础。尽管这些原则起源于面向对象编程 (oop),但它们可以有效地应用于 javascript (js) 和 typescript (ts) 框架,例如 react 和 angular。本文通过 js 和 ts 中的实际示例解释了每个原理。

1.单一职责原则 (srp)

原则:一个类或模块应该只有一个改变的理由。它应该负责单一功能。

javascript 示例(react):

在 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 
{user?.name}
;}

此处,userprofile 组件违反了 srp,因为它同时处理 ui 渲染和数据获取。

立即学习“Java免费学习笔记(深入)”;

重构:

// custom hook for fetching user datafunction 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 componentfunction userprofile({ userid }) {  const user = useuserdata(userid); // moved data fetching logic to a hook  return 
{user?.name}
;}

通过使用自定义钩子 (useuserdata),我们将数据获取逻辑与ui分离,让每个部分负责单个任务。

typescript 示例(angular):

在 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),我们确保每个类都有单一职责。

2.开闭原则 (ocp)

原则:软件实体应该对扩展开放,对修改关闭。这意味着您应该能够扩展模块的行为而不更改其源代码。

javascript 示例(react):

您可能有一个运行良好的表单验证功能,但将来可能需要额外的验证逻辑。

反模式:

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。

typescript 示例(angular):

在 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本身。

3.里氏替换原理 (lsp)

原则:子类型必须可以替换其基本类型。派生类或组件应该能够替换基类而不影响程序的正确性。

javascript 示例(react):

当使用高阶组件 (hoc) 或有条件地渲染不同组件时,lsp 有助于确保所有组件的行为可预测。

反模式:

function button({ onclick }) {  return ;}function linkbutton({ href }) {  return click me;}

这里,button 和 linkbut​​ton 不一致。一个用onclick,一个用href,替换起来很困难。

重构:

function clickable({ children, onclick }) {  return 
{children}
;}function button({ onclick }) { return ;}function linkbutton({ href }) { return window.location.href = href}> click me ;}

现在,button 和 linkbut​​ton 的行为类似,都遵循 lsp。

typescript 示例(angular):

反模式:

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。

4.接口隔离原则(isp):

原则:客户端不应该被迫依赖他们不使用的接口。

javascript 示例(react):

react 组件有时会收到不必要的 props,导致紧密耦合和庞大的代码。

反模式:

function multipurposecomponent({ user, posts, comments }) {  return (    
);}

这里,组件依赖于多个 props,即使它可能并不总是使用它们。

重构:

function userprofilecomponent({ user }) {  return ;}function userpostscomponent({ posts }) {  return ;}function usercommentscomponent({ comments }) {  return ;}

通过将组件拆分为更小的组件,每个组件仅取决于它实际使用的数据。

typescript 示例(angular):

反模式:

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 接口,我们确保客户只依赖他们需要的东西。

5.依赖倒置原则(dip):

原则:高层模块不应该依赖于低层模块。两者都应该依赖于抽象(例如接口)。

javascript 示例(react):

反模式:

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 
{user?.name}
;}

这里,usercomponent 与 fetchuser 函数紧密耦合。

重构:

function usercomponent({ userid, fetchuserdata }) {  const [user, setuser] = usestate(null);  useeffect(() => {    fetchuserdata(userid).then(setuser);  }, [userid, fetchuserdata]);  return 
{user?.name}
;}// usage;

通过将 fetchuserdata 注入到组件中,我们可以轻松地更换测试或不同用例的实现。

typescript 示例(angular):

反模式:

@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;}@Injectable()export class ApiUserService implements 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));  }}

通过依赖接口(userservice),usercomponent 现在与 apiuserservice 的具体实现解耦。

后续步骤

无论您是使用 react 或 angular 等框架开发前端,还是使用 node.js 开发后端,solid 原则都可以作为指导,确保您的软件架构保持可靠。

要将这些原则完全融入您的项目中:

定期练习:重构现有代码库以应用 solid 原则并审查代码是否遵守。与您的团队合作:通过代码审查和围绕干净架构的讨论来鼓励最佳实践。保持好奇心:坚实的原则仅仅是开始。探索基于这些基础知识的其他架构模式,例如 mvc、mvvm 或 cqrs,以进一步改进您的设计。

结论

solid 原则对于确保代码干净、可维护和可扩展非常有效,即使在 react 和 angular 等 javascript 和 typescript 框架中也是如此。应用这些原则使开发人员能够编写灵活且可重用的代码,这些代码易于随着需求的发展而扩展和重构。通过遵循 solid,您可以使您的代码库变得强大并为未来的增长做好准备。

以上就是在 JavaScript 和 TypeScript 框架中应用 SOLID 原则的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493210.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 15:29:52
下一篇 2025年12月19日 15:30:07

相关推荐

发表回复

登录后才能评论
关注微信