The typechecker considers this class requirement by the interface IBase to be cyclic:
<?hh // strict
interface IBase {
require extends Derived;
}
class Derived implements IBase {}
// Cyclic class definition : IBase Derived (Typing[4013])
As I understand it, the constraint just prevents all descendants from implements IBase without extends Derived. Is there a hole with this that I'm not seeing?
Why do I care?
I'm interested in an interface that wants to compare against other instances of itself or its subtypes.
<?hh // strict
interface Comparable<-T as Comparable<T>> {
require extends ArtificialCeiling;
public function compare(T $comparee): bool;
}
abstract class ArtificialCeiling implements Comparable<ArtificialCeiling> {
abstract public function compare(ArtificialCeiling $comparee): bool;
}
(this is not the answer here, because this isn't sound in contravariant positions, especially in interfaces)
Suppose now we want to accept and store a wrapper of Comparable but we don't care about what type of Comparable it's lugging around. Normally, we'd just parameterize with the upper bound, or mixed if its unconstrained.
The problem is that the upper bound for Comparable is Comparable<Comparable<Comparable<... forever, but I don't have the stamina to type that for all eternity. Without existential types like Scala or multiple constraints like TComparable as Comparable & ArtificialCeiling, we have to resort to something less obvious. require extends ArtificialCeiling would be just like a multiple constraint and, without this mysterious cyclic problem, it would be a tidy fix.
The other natural alternative is for the accepting class to append the parameter to its own parameter list as TComparable as Comparable<TComparable>, but that defeats the principle of not caring about TComparable.
Well, I'm not an expert, but the message seems clear to me:
the definition is cyclic, because Derived uses IBase and IBase references Derived.
According to the documentation:
require extends should be taken literally. The class must extend the
required class; thus the actual required class does not meet that
requirement. This is to avoid some subtle circular dependencies when
checking requirements.
I think the way to go is to specify the requirement for an ancestor class, and implement the interface in the non-abstract derived class(es). Or maybe just implement compare as a normal method in the ancestor class, instead of using a trait.
Related
I'm trying to build a better Flowtype definition for Koa library and am kinda stuck.
My idea was to use Generic types to be able to specify customized Context class to Koa, so we can actually typecheck additional fields (populated by middlewares) instead of treating them as any.
so, I have:
declare type Context {…}
declare class Application<T: Context<T>> extends events$EventEmitter {
context: T,
…
}
fine…
but Context has a back-reference to Application, which is a generic dependent on Context. How do I spell this in typelib?
This doesn't look right, as I actually want to use not original Context but the type which was actually used by user
declare type Context {
app: Application<Context>
}
Given the following classes
abstract class SomeAbstractClass { abstract val name: String }
data class DataClass( override val name: String ) : SomeAbstractClass()
class NoDataClass( override val name: String ) : SomeAbstractClass()
For any instance of SomeAbstractClass, can I determine whether it is a data class without relying on type checking?
Some background: this seemed the best way of combining inheritance and data classes to me, as suggested in a different answer. Now, within the initializer block of SomeAbstractClass, I want to throw an exception in case the derived type is not a data class to ensure 'correct' (immutable) implementations of derived types.
Using reflection, the Kotlin class description (KClass) can be obtained using the ::class syntax on the instance you want to investigate (in your case, this::class in the initializer block of the abstract class). This gives you access to isData:
true if this class is a data class.
However, as Oliver points out, data classes can still contain var members, so you likely also want to check whether all member variables (and their member variables recursively) are defined as val to ensure immutability of all deriving classes.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
could some body explain me abstraction and interface in asp.net, C# by taking an apprpriate example...pleasse
i am not understanding it for long
I often find the following sample quite illuminating when it comes to explaining this:
Disclaimer: the code examples are written directly into the text, and may contain errors that I have overseen. Please let me know if you find such errors.
Let's say you have a database with a Customer table, and in your code you have a customer class:
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
In order to provide a mechanism to get customer data from the database, you need to write some class doing that. This can be placed in something called a repository. Now, we don't want our code to rely too much on what exact database we use. It could be SQL server, it could be a text file. So we want an abstraction layer shielding the code from this knowledge. All we need to know is what such a repository looks like:
public interface ICustomerRepository
{
Customer GetCustomer(int id);
IEnumerable<Customer> FindCustomers(string beginningOfName);
}
We can now implement this interface for the data storage that we use:
public class SqlServerCustomerRepository : ICustomerRepository
{
public Customer GetCustomer(int id)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
// code to fetch data and populate Customer objects go here
}
}
// implementations of other members of ICustomerRepository
// left out to keep code short. Just imagine they are here :)
}
Finally, when we want to use this code, we can have a factory create the concrete ICustomerRepository implementation to use:
public static class RepositoryFactory
{
public static ICustomerRepository CreateCustomerRepository()
{
return new SqlServerCustomerRepository();
}
}
...and in our code where we need the data:
ICustomerRepository repository = RepositoryFactory.CreateCustomerRepository();
IEnumerable<Customer> customers = repository.FindCustomers("A");
This way, there is no hard coupling between the consuming code, and the particular kind of repository in use (except for in the factory method, but that is the one and only place where this knowledge exists). This makes it easy to replace the concrete repository implementation. This is also useful for testing, where you can easily create a mock repository returning hard coded results for given input, so that you can unit test the code that needs data from the repository.
Well abstract classes and interfaces are not strictly asp.net technic they are OOP concept.
Interface
An interface is like a class but all the methods and properties are abstract. An Interface cannot be instantiated like abstract class. All the methods and properties defined in Interface are by default public and abstract.
Interface generally refers to an abstraction that an entity provides of itself to the outside. Interface can help in separating the methods for external and internal communication without effecting in the way external entities interact with the type..
Example:
If you have interface IDoSomething { void Do(); }
The class that implements the interface must provide a body for Do() method e.g.
class SomeClass : IDoSomething
{
public void Do()
{
//body of the method
}
}
The advantage of this is when you make something that need only Do method you pass the interface not the class.
public static void SomeMethod(IDoSomething obj)
{
obj.Do();
}
Now SomeMethod(IDoSomething obj) will work with any class that implements IDoSomething
Abstract Class
An abstract class is a class with at least one method defined as abstract. This type of class cannot be instantiated. An abstract class can have one or more abstract methods and properties and other methods and properties like normal classes.
The idea is the same but in abstract class you can have methods with implemented logic, fields and so on.
Abstraction
Abstraction is the process of hiding how the object is working, and its only showing the information of the object the way we can understand it. Means it represent the essential details with out showing ground details. We putting all variables and method in a class which are necessary.
Eg: Employee and Patient.
Company interested to fill about the Employee details like Name, Address, Qualification, DOB, Age, Mobile, Marks, Experience etc
Hospital interested to fill about the patient details like Name, DOB, Height, Weight, Age, Address, Mobile, Blood Group etc.
Both Company and hospital interested to fill some common fields like Name, Age, DOB, Address, Mobile etc. So we can create a class which consist of common thing that is called abstract class. This class wont be complete but can inherit by other class.
Abstract vs Interface
You cannot create an object of abstract class , but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
Defining an abstract class with all the abstract members is similar to defining an interface. i.e we can say an interface is an abstract class with all the abstract members
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
1). If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2). If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3). If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4). If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language. It should be [mostly] obvious how to apply it in different languages.
If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.
This is easy enough. But I don't understand why you have the capacity to cast an interfaced instance back to its original base class. Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)
Here's a sample interface:
public interface IFooable extends IUIComponent {
function runFoo():void;
}
Let's say I create a base class, which extends VBox and implements the interface:
public class Foo extends VBox implements IFooable {
public Foo() {
super();
//stuff here to create Foo..blah blah
}
public function runFoo():void {
// do something to run foo
}
}
Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented. It is a common piece of functionality all of my classes should have, regardless of how they implement it. Thus, my parent class (an Application) will instantiate Foo via its interface:
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100; //works because of IUIComponent
}
But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100;
addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type
//could also do this:
//addChild(foo as VBox);
}
Wasn't the original intention to hide the implementation of Foo? There is still an assumption that Foo is a DisplayObject. Unfortunately, being able to add the custom object to a container seems impossible without casting.
Am I missing something entirely? Is this really just a phenomenon in Flex/AS3? If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?
For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).
2nd Thought:
Abstract Classes:
As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface. Thus, any class which extends the abstract class would then be required to implement the methods therein.
Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).
So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor. Unfortunately, this is run-time checking as opposed to compile-time enforcement.
It's still a solution, though.
Context:
Some context might help:
I have an application which can have any number of sub-containers. Each of these sub-containers will have their own respective configuration options, parameters, etc. The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options. Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu. This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.
Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar. But when I add them to the application, they need to be the base class.
#James Ward, That's definitely something I wish was in the language, probably a interface IDisplayObject. That would solve a lot of issues in OOP display programing in AS3.
In regards the the original question, something I've used in the past, and have seen mentioned on www.as3dp.com is to include a getDisplay():DisplayObject method in the interface, which would typically return "this" by its implementor. It's less than ideal, but works.
#Matthew Flaschen, While we don't have Abstarct Classes native to AS3, common practice is to name the class with the word Abstract ie: AbstarctMyObject, and then just treat it like the abstarct objects in Java and other languages. Our want for true abstarct classes is something the Flash player team is well aware of, and we'll likly see it in the next version of the ActionScript language.
Okay, I'm anaswering generally, because you said, "Is this really just a phenomenon in Flex/AS3?".
In your init method, obviously you're always calling addChild with foo. That means foo must always be an instance of DisplayObject. You also want it to be an instance of IFooable (though it's not clear here why). Since DisplayObject is a class, you would consider using a subclass of DisplayObject (e.g. FooableDisplayObject), that implemented IFooable. In Java, this would the below. I'm not familiar with AS, but I think this shows there's not any general flaw in interfaces here.
interface IFooable
{
public void runFoo();
}
class DisplayObject
{
}
abstract class FooableDisplayObject extends DisplayObject implements IFooable
{
}
class Foo extends FooableDisplayObject
{
public void runFoo()
{
}
}
public void init()
{
FooableDisplayObject foo = new Foo();
foo.percentHeight = 100;
addChild(foo);
}
I think this is a place where Flex's/Flash's API is not correct. I think that addChild should take an interface not a class. However since that is not the case you have to cast it. Another option would be to monkey patch UIComponent so that it takes an interface or maybe add another method like addIChild(IUIComponent). But that's messy. So I recommend you file a bug.
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.
Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.
Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.
Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.
public class Page extends Sprite{...}
public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
public class Homepage extends Page implements IPageLoader
{ function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }
var currentpage:Page;
var currentpageLoader:IPageLoader;
currentpage = new Homepage;
currentpageLoader = currentpage as IPageLoader;
currentpageLoader.loadPage();
currentpageLoader.initPage();
addChild(currentpage);
Tween(currentpage, x, CENTER);
Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.