Interface inheriting Type script - oop

I just want to write a User module which has multiple classes i.e. UserDetail,UserResestPassword so on .
There are some common properties which these classes are going to share , one approach I can declare property on every class and Initialize it.
The second approach is I will use of inheritance this will need to declare in
interface
export interface Iuser {
UserID:string;
UserName:string
}
and implement it into classes
import {Iuser} from './IuserDetail'
class UserInfo implements Iuser {}
My question is, is't supported in typescript? if not what are the way around to sort out this

In TypeScript there is a feature called "type erasure" where all of the type information is removed during compilation so the JavaScript output contains no type annotations, interfaces, or ambient declarations - only real code.
This means that when you ask your module loader (at runtime) to get you the Iuser interface, it doesn't exist in the JavaScript file.
My recommendation would probably be to put your interfaces in files with their primary implementation. That means you don't end up attempting to load a module that is just a blank file.
For example:
export interface Iuser {
UserID:string;
USerName:string
}
export class UserInfo implements Iuser {
}
And in other files you can:
import * as User from './UserInfo'
export class Example implements User.Iuser {
}

Look at this example:
Interfaces don't actually exist after compilation but are strictly used for type checking.
// i-user.ts
export interface IUser {
UserID:string;
UserName:string
}
Just like interfaces in other languages you have to implement all members of an interface. TypeScript will check if you are missing any.
// user-info.ts
import { IUser } from './i-user'
export class UserInfo implements IUser {
UserID:string;
UserName:string;
OtherInfo:string;
}
Using extend all parent methods will be available and you don't need to implement them again.
// specific-user-info.ts
import { UserInfo } from './user-info'
class SpecificUserInfo extends UserInfo {
logInfo() {
console.log(this.UserID, this.UserName);
}
}

Related

Is it possible to extend classes and still use DSON Generator for Dart?

I have dart web app using sdk 1.24 and have been using dson: 0.11.0 to generate serializable classes/models for my objects that are being saved to a firestore database.
I love the way the dson generated classes give me the ability to create a dart object from a map, or serialize a dart object to a map for saving in firebase.
With that said, the dson generator requires my model class to extend a serializable abstract generated class.
My application is starting to grow rather large and I am struggling with the inability to use inheritance and develop a class hierarchy.
Unless I am missing some concept that I can't seem to crack on my own, I cannot figure out how to use class inheritance with the dson generator.
For example, here is a really simple example of what I am trying to do.
class EmploymentIncome extends Object {
String employerName;
Address employerAddress;
DateTime hireDate;
}
class SalaryIncome extends EmploymentIncome {
double annualSalary;
}
class HourlyIncome extends EmploymentIncome {
double hourlyRate;
double hoursPerWeek;
}
class hourlyPaystub extends HourlyIncome {
double yearToDateHourlyEarnings;
double hoursWorked;
DateTime payDate;
DateTime periodEndingDate;
}
class salaryPaystub extends SalaryIncome {
double yearToDateSalaryEarnings;
DateTime payDate;
DateTime periodEndingDate;
}
The problem is, the dson generator requires my models to extend the generated abstract class, see below:
#serializable
class EmploymentIncome extends _$EmploymentIncomeSerializable {
class EmploymentIncome extends Object {
String employerName;
Address employerAddress;
DateTime hireDate;
}
The problem, obviously, is now, I cannot extend EmploymentIncome with another serializable dson class.
Am I missing a fundamental concept or technique that would allow me to extend these classes while still maintaining the ability to convert dart objects to and from maps?
Thank you in advance for any guidance!
Two things need to be done:
extend generated serializable class using with operator
add comment to ignore analysis error
For example in your case you can do:
#serializable
class EmploymentIncome extends _$EmploymentIncomeSerializable {
String employerName;
Address employerAddress;
DateTime hireDate;
}
#serializable
// ignore: mixin_inherits_from_not_object
class SalaryIncome extends EmploymentIncome with _$SalaryIncomeSerializable {
double annualSalary;
}
#serializable
// ignore: mixin_inherits_from_not_object
class HourlyIncome extends EmploymentIncome with _$HourlyIncomeSerializable {
double hourlyRate;
double hoursPerWeek;
}
#serializable
// ignore: mixin_inherits_from_not_object
class HourlyPaystub extends HourlyIncome with _$HourlyPaySerializable {
double yearToDateHourlyEarnings;
double hoursWorked;
DateTime payDate;
DateTime periodEndingDate;
}
#serializable
// ignore: mixin_inherits_from_not_object
class SalaryPaystub extends SalaryIncome with _$SalaryPayStubSerializable {
double yearToDateSalaryEarnings;
DateTime payDate;
DateTime periodEndingDate;
}
I'm not really familiar with package:dson, but having used and written various serialization code generators, it all boils down to knowing: What class should be created given the input?
In most cases the serialized format does not contain the class information (it is too verbose to store it), and the library can't really decide whether the superclass or the subclass needs to be instantiated for a given input. I suspect that this is the case for dson too.
In most cases you will have better performance and you can remain future-proof if you use composition instead of inheritance. Check out the answer for a similar questions with protobuf.

declaring a method as optional in abstract class

As far as I've understood in Dart is possible to use abstract classes to declare "interfaces" or "protocols" (if you come from objective-c).
Anyway I'm having trouble in finding a way to declare an optional method in the abstract class/interface.
If I declare a method in the abstract class A, and let the concrete class B implement A, I get a warning in the compiler.
I'd like to be able to declare a method as optional or at least to provide a default implementation without needing to "re-declare" it in a class that implements my interface.
abstract class A{
void abstractMethod();
}
class B implements A{
//not implementing abstract method here gives a warning
}
That's not how interfaces work. If your class states to implement an interface, then this is what it has to do.
You can split the interface
abstract class A {
void abstractMethod();
}
abstract class A1 extends A {
void optionalMethod();
}
class B implements A {
//not implementing abstract method here gives a warning
}
only when it states to implement A1 it has to implement optionalMethod.
Alternatively you can extend the abstract class
abstract class A{
void abstractMethod();
void optionalMethod(){};
}
class B extends A {
//not implementing abstract method here gives a warning
}
then only abstractMethod needs to be overridden because A doesn't provide an implementation.
Abstract methods defined in classes cannot be marked as optional. (At least not in the regular Dart language, I don't know of annotations that might support something like this.)
Any class that implements an interface must provide an implementation of all abstract methods, but, those method implementations may trivially throw an error to indicate that the method is not available.
Throw UnimplementedError if the implementing class is incomplete and the proper implementation is to be added later
Throw UnsupportedError if the implementing class does not intend to implement the method.
Note that UnimplementedError implements UnsupportedError.
Obviously you have to be judicious about what you choose to not implement. If it's in code that is not intended to be shared you can get away only implementing methods that you explicitly know are required. If it's in a library package intended to be shared with others you would need a good reason to not implement a method, and that reason should be well documented.
Example code:
abstract class A {
void abstractMethod();
}
class B implements A {
void abstractMethod() { throw new UnimplementedError(...); }
// or
void abstractMethod() { throw new UnsupportedError(...); }
}
See:
https://api.dartlang.org/stable/1.18.1/dart-core/UnimplementedError-class.html
https://api.dartlang.org/stable/1.18.1/dart-core/UnsupportedError-class.html

OOP design suggestion for inheritance

abstract class db{
// return an handle to db
}
class type extends db{
// code that uses db
}
abstract class limits extends db{
// code that DOES NOT use db
}
class otherclass extends limits{
// code that use db and limits
}
As you can see, I need db in all classes except limits. But limits is parent for classes that use db.
I think this is not the correct design pattern, since I extend db in limits just to have db available for children. Or is it?
Thanks.
Depending on unstated requirements, you would be better off with composition instead of inheritance, in this case.
class db {
// returns db handle
}
class type {
private db; // type can now use db
}
class limits {
// does something
}
class otherclass {
private limits;
private db; // can use limits and db
}
You said " I need db in all classes except limits." which indicates you should compose (or contain) a db not inherit from it. See md4's answer.
You need to think about why you might have abstract classes - this is usually because you want to "program to an interface" to coin a phrase.
Perhaps db and limits are two different things - think single responsibility...
abstract class db {
// returns db handle
}
abstract class limits {
// does something
}
class otherclass : extends limits, db {
}
...edit start...
Clearly for some specific OO languages like Java and C# limits and db would need to be interfaces rather than classes. The OP didn't specify a language.
...edit end...
Think about the using code - consider writing a few unit tests to see what it looks like. Think about what must change together and what should be decoupled.

Singleton subclass

I have an abstract base class and an implementation class like:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
//expected to return a singleton instance of clazz's class
}
public abstract absMeth();
}
public A extends Base
{
//expected to be a singleton
}
In this example I can make A to be a singleton and even write getInstance in Base to return a singleton object of A for every call, doing this way:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
try
{
return clazz.getDeclaredMethod("getInstance").invoke(null,null);
}
}
public abstract void absMeth();
}
public A extends Base
{
private static A inst;
private A(){}
public static A getInstance( )
{
if( inst!= null)
inst = new A();
return inst;
}
public void absMeth(){
//...
}
}
But my concern is how do I ensure that if somebody writes another class class B extends Base it should also be a singleton and it necessarily implements a static method called getInstance?
In other words I need to enforce this as a specification for all classes extending with the Base class.
You cannot trust classes that extend you to create a single instance of themselves1: even if you could somehow ensure that they all implement getInstance, there is no way to tell that inside that method they check inst before constructing a new instance of themselves.
Stay in control of the process: create a Map<Class,Base>, and instantiate the class passed in through reflection2. Now your code can decide whether to create an instance or not, without relying on the getInstance of a subclass.
1 A popular saying goes, "If you want a job done right, do it yourself."
2 Here is a link describing a solution based on setAccessible(true)
Singleton is a design pattern, not a language feature. It is pretty much impossible to somehow enforce it on the inheritance tree through syntax.
It certainly is possible to require all subclasses to implement a method by declaring it abstract but there is no way to control implementation details. Singleton is all about implementation details.
But why is this a concern at all? Do not make your app dependant on internal details of someone else's code. It is Bad Design™ and having this issue is a sure sign of it. Code against a well-defined interface and avoid relying on internal details.

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.