You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classPerson{// ! 构造器参数逐渐增加、构造逻辑逐渐复杂constructor(firstName: string,lastName: string,age: number,address: string,gender: string,maxWeight: number,minWeight: number){// ! 复杂校验逻辑if(!firstName)thrownewError('firstName cannot be undefined');if(!lastName)thrownewError('firstName cannot be undefined');if(!age)thrownewError('firstName cannot be undefined');if(!address)thrownewError('firstName cannot be undefined');if(!gender)thrownewError('firstName cannot be undefined');if(!maxWeight)thrownewError('firstName cannot be undefined');if(!minWeight)thrownewError('firstName cannot be undefined');if(minWeight>maxWeight)thrownewError('minWeight should not more than maxWeight');this._firstName=firstName;this._lastName=lastName;this._age=age;this._address=address;this._gender=gender;this._minWeight=minWeight;this._maxWeight=maxWeight;}}// 可读性和易用性都很差: 参数名称一眼看不出来、参数顺序可能输错constjames=newPerson('James','Wang',30,'46 Maria Road','male',85,60);console.log(james);
// pros: easy to read and use (client-side)// pros: easy to extend field validation logic based on class-validator// pros: easy to extend integration validation logic based on DTOBase class code reuse// cons: have to declare types// pros > consconstjames2: Person2=Person2.fromObject({firstName: 'James2',lastName: 'Wang',age: 30,address: '46 Maria Road',gender: 'male',minWeight: 30,maxWeight: 60,});
// pros: read to read and use (client-side)// cons: has to add field validation logic manually (or you still use class-validator)// cons: some parts of source code is redundant// pros < consconstjames3=newPerson3.Builder().setFirstName('James').setLastName('Wang').setAge(30).setAddress('46 Maria Road').setGender('male').setMinWeight(30).setMaxWeight(100).build();