I want to use OCP rule in my "small" project. Actually i have a problem with implementing this one. Let me show you what have i wrote.
abstract class AnimationType {
public abstract createAnimation(timing: number): { in: string, out: string };
}
class FadingAnimation extends AnimationType {
public createAnimation(timing: number): { in: string, out: string } {
return { in: 'opacity: 0', out: 'opacity: 1' }
}
}
class TransformAnimation extends AnimationType {
public createAnimation(timing: number): { in: string, out: string } {
return { in: 'transform: translateX(-100%)', out: 'transform: translateX(100%)' }
}
}
class AnimationCreator {
private timing: number;
constructor(time: number) {
this.timing = time;
}
getAnimation(animation: AnimationType): { in: string, out: string } {
return animation.createAnimation(this.timing);
}
}
Do I write it good? If I do, then what actually i have gained? I need to send object of FadingAnimation class if i want to add this animation. If i want transform animation i need to send object of TransformAnimation class - so somewhere i have to use switch(this.animationType).
Principles and patterns are absolutely transferable between languages. They may be less applicable when you cross the bounds of a paradigm. SOLID principles and OOP patterns apply to any object-orientation, not just Java.
Remember that TypeScript/JavaScript are not just object-oriented though.
The problem isn't that you are attempting to draw from principles that come from other languages. The problem here is that you are attempting to start with the principle.
Good code design, whatever paradigm you use, starts with a problem that you want to solve. Write more code before looking for patterns or applying principles, so the design can emerge from the real problems you find as your application grows.
By starting with a principle, you are deciding too early what the problem may eventually be; and your design may take you further away from the goal of clean code.
Patterns and principles are highly transferable, but wait for signals that you have a problem, rather than prematurely applying some solution.
In your case, you can just solve the problem the simplest way. If you have a test to guide you, you can easily update the implementation details later.
Perhaps in your case, a simple dictionary/object would be sufficient.
const animationType = {
fading: {
in: 'opacity: 0',
out: 'opacity: 1'
},
transforming: {
in: 'transform: translateX(-100%)',
out: 'transform: translateX(100%)'
}
};
You could type this to allow any key, if you didn't want to enforce fading
and transforming
- but you don't need to add this flexibility yet:
interface AnimationTypes {
[key: string]: { in: string, out: string };
}