Reputation: 281
I have two classes that extend abstract class:
class SubstitutionTeacher extends SubstitutionAbstract {
abstract _save();
}
class SubstitutionFree extends SubstitutionAbstract {
public _save() {
}
}
class SubstitutionSubject extends SubstitutionAbstract {
public _save() {
}
}
In method save()
I realize own behaviour like this:
/* Class SubstitutionFree
public _save() {
const substitutionAdd: ISubstitutionModelTeacher = {
lesson: this.substitution.lessonNumber,
confirmed: true,
subsDate: this.substitution.date,
newTeacher: this.substitution.teacher
};
return this.replaceService.addSubstitution(substitutionAdd);
}
/* Class SubstitutionSubject
public _save() {
const substitutionAdd: ISubstitutionModelTeacher = {
lesson: this.substitution.lessonNumber,
confirmed: true,
newTeacher: this.substitution.teacher
};
return this.replaceService.addSubstitution(substitutionAdd);
}
As you can see both method are almost similar. I want to avoid this duplication:
{ lesson: this.substitution.lessonNumber,
confirmed: true,
newTeacher: this.substitution.teacher
}
I can change save()
to regular save()
and pass there a common part but it losts meaning of abstraction.
Upvotes: 2
Views: 84
Reputation: 5354
This might be invalid typescript, just because I am not that good in typescript :)
But your problem is not typescript specific, so maybe this will give you an idea of how such problems can be fixed.
Create a method in SubstitutionAbstract
:
class SubstitutionAbstract {
// this one should be called each time you need that object instead of duplicating
// you can make it protected if there is such stuff in typescript
public getMyStuff(param1, param2, param3, param4) {
return { lesson: param1,
confirmed: param2,
newTeacher: param3,
subsDate: param4
};
}
// .....
}
In each your subclass just call it:
public _save() {
const substitutionAdd: ISubstitutionModelTeacher =
getMyStuff(this.substitution.lessonNumber, true,
this.substitution.date, this.substitution.teacher);
return this.replaceService.addSubstitution(substitutionAdd);
}
If you don't need subsDate
in some implementation then pass null
for that one to getMyStuff
, don't think it can be a problem. Typescript probably checks types etc., so you might need to play with that method to make work (e.g. it should return something of type ISubstitutionModelTeacher
I guess).
And again - this is probably not working code, because typescript is not my area, but it describes the idea of how you could do.
And sure there could be other ways, this is just 1 example.
Happy Coding :)
Upvotes: 1