Solidity Ide- interface error: Contract "Cat" should be marked as abstract - interface

I'm new with Solidity, and used version 0.8.7 !
I'm practice abstract contract and interface but get this error : Contract "Cat" should be marked as abstract.
And here it's my code below.
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
abstract contract Animal {
uint8 head = 1;
function braking() public virtual pure returns(string memory);
}
interface get {
function getHeadNumber() external returns(uint8);
}
contract Dog is Animal, get{
function braking() public override pure returns(string memory) {
return "Woof!!";
}
function getHeadNumber() public override view returns(uint8) {
return head;
}
}
contract Cat is Animal, get { < < < error here !!!!
function braking() public override pure returns(string memory) {
return "Meow!!";
}
function getHeadnumber() public override view returns(uint8) {
return head;
}
}
I want to know why contract Dog can without abstract, but contract Cat can't !!
If u need detail error messages
Sorry for my bad English, hopes you have a wonderful day.
Many Many thanks!!!

Pay attention to case sensitivity:
The interface get defines getHeadNumber() (capital N in Number).
But the contract Cat is trying to override getHeadnumber() (lowecase n in number).
Solution: Rename the function in contract Cat to getHeadNumber() (capital N).

Related

Swift: how to understand dynamic method dispatching in init method?

I find that the dynamic method dispatching in init method of Swift is different from which in C++, can anyone explain why?
This is the demo code and its output:
In Swift:
class Object {
init() {
a()
}
func a() {
print("Object")
}
}
class SubObject: Object {
override init() {
}
override func a() {
print("SubObject")
}
}
let a = SubObject()
// output: SubObject
In C++:
class Object {
public:
Object() {
a();
}
virtual void a() {
std::cout << "Object" << std::endl;
}
};
class SubObject: public Object {
public:
SubObject() {
}
virtual void a() {
std::cout << "SubObject" << std::endl;
}
};
int main(int argc, const char * argv[]) {
SubObject s;
return 0;
}
// output: Object
As you can see, these code above write in Swift and C++ are nearly the same, but their output is quite different, while Swift seems that it finds the override method and called the derived one, the C++ still called the super's.
Here at LearnCpp, it says:
Do not call virtual functions from constructors or destructors Here’s another gotcha that often catches unsuspecting new programmers. You should not call virtual functions from constructors or destructors. Why?
Remember that when a Derived class is created, the Base portion is constructed first. If you were to call a virtual function from the Base constructor, and Derived portion of the class hadn’t even been created yet, it would be unable to call the Derived version of the function because there’s no Derived object for the Derived function to work on.
In C++, it will call the Base version instead.
A similar issue exists for destructors. If you call a virtual function in a Base class destructor, it will always resolve to the Base class version of the function, because the Derived portion of the class will already have been destroyed.

Is it possible for protocols to have a default implementation of static factory methods?

Consider a protocol that have a factory method:
public protocol Frobnicator {
func frobnicate()
static func makeRightFrobnicator() -> Frobnicator
}
private class SomeFrobnicatorImplementation: Frobnicator { ... }
private class AnotherFrobnicatorImplementation: Frobnicator { ... }
public extension Frobnicator {
static func makeRightFrobnicator() -> Frobnicator {
if something {
return SomeFrobnicatorImplementation()
} else {
return AnotherFrobnicatorImplementation()
}
}
}
I want to be able to construct different implementors at different times. The implementors themselves are private to the module, whereas the protocol is public to use in the client code.
When I try the code similar to that above, I get “Static member makeRightFrobnicator cannot be used on protocol metatype Frobnicator.Protocol.”
Is there any way around it, or should I just use a free function?
The static function implementation is legal:
protocol P {
static func f() -> P
init()
}
extension P {
static func f() -> P {return self.init()}
}
But you'll notice that in order to get it to compile, I had to guarantee to the compiler that I have in hand a legal way to make a P so as to able to return one.
The issue in your code is the attempt to return a specific adopter of your protocol, like a SomeFrobnicatorImplementation. A protocol is agnostic as to who adopts it. To put it another way, you cannot guarantee within the protocol definition that SomeFrobnicatorImplementation will in fact be an adopter of this protocol. Thus, that part of your code is illegal.

How to design the classes with OOP?

I have problems about classes design now. The question is as follows:
I want to design classes for fruit and juicer. The classes for fruit (Apple, pear peach) are done. Now I want to design classes for juicer.
The requirement for juicer are:
1.Juicers take specific fruit (apple, pear, peach) and produce juice. NOTE: there may be mixed juice (such as flavor of apple and pear).
2.One kind of juicer can only produce one kind of juice.
3.Juicers have space to store fruit, and we can know how many apples or pears are still there. (We assume that every time one juicer uses one apple or pear).
Could anyone give me some advices?
If your language supports generics (as do C# and Java), the simplest solution would be to make the Juicer generic:
public class Juicer<T>
{
private T[] fruits;
public Juicer(T[] fruits)
{
this.fruits = fruits;
}
public FruitCount
{
get { return this.fruits.Length; }
}
// Other members can go here...
}
You can create one object that's a Juicer<Apple>, another as a Juicer<Pear>, and so on. A Juicer<Apple> can only contain Apple objects, etc.
Mark's answer is pretty good and a good start... I'd expand a bit. I probably wouldn't use an array for fruits since you will be adding, removing etc... probably easier to implement with a list or similar. Also, Laine says he wants multiple fruits in some juicers.. that complicates things a bit and gives us some decisions to make.
If it will always be a maximum of two fruits, I would probably just make two juicer classes similar to those in Mark's answer:
public interface IFruit
{
string Name {get;}
}
public class Apple : IFruit
{
public string Name { get {return "Apple";} }
}
public class Pear : IFruit
{
public string Name { get {return "Pear";} }
}
public class Juicer<IFruit>
{
private IList<IFruit> fruits;
public Juicer(IList<IFruit> fruits)
{
this.fruits = fruits;
}
public int FruitCount
{
get { return this.fruits.Count; }
}
// Other members can go here...
}
public class TwoFruitJuicer<IFruit, IFruit2>
{
private IList<IFruit> fruits;
private IList<IFruit2> fruits2;
public TwoFruitJuicer(IList<IFruit> fruits, IList<IFruit2> fruits2)
{
this.fruits = fruits;
this.fruits2 = fruits2;
}
public int FruitCount
{
get { return this.fruits.Count + this.fruits2.Count; }
}
// Other members can go here...
}
But, say you wanted 3 or 4 different juicers combined...
public class MulitJuicer
{
private IList<Juicer<IFruit>> _juicers;
public MulitJuicer(IList<Juicer<IFruit>> juicers)
{
this._juicers = juicers;
}
public int FruitCount
{
get {
int allFruitCount = 0;
foreach (var j in _juicers)
{
allFruitCount += j.FruitCount;
}
return allFruitCount;
}
}
}
However, That would probably be pretty difficult to use, a lot of lists inside of lists to keep track of build up and whatnot... what if you wanted just once juicer that you could just dump a bunch of fruits in? We can use Reflection to verify that only allowed fruits are put in the juicer:
public class MultiFruitJuicer
{
private IList<Type> _juiceTypes;
private IList<IFruit> _fruits;
public MultiFruitJuicer(IList<Type> juiceTypes, IList<IFruit> fruits)
{
_juiceTypes = juiceTypes;
_fruits = fruits;
if (!ValidateFruits())
{
//you may not want to actually throw here...
throw new Exception("Not all proper fruit types");
}
}
public bool ValidateFruits()
{
//there are about a million ways to do this... this is probably not the best...
foreach(var f in _fruits)
{
if (!_juiceTypes.Contains(f.GetType()))
{
return false;
}
}
return true;
}
public int FruitCount
{
get { return this._fruits.Count; }
}
}
I would start by implementing Builder design pattern for the
design classes for juicer
It'll help you to construct a complex object (juice) and separate its representation, so that the same construction process can create different representations (kinds of juice).
Add some interface (IFruit) and base class (shared code for Weight, Size etc.) to
classes for fruit (Apple, pear peach)
Each Juicer will have
ICollection<IFruit> fruits
that can be managed - .Count(), .Add(IFruit) or .Remove(IFruit).

final interface implementation not recognized from interface base list

How can a method from the InterfaceBaseList be implemented in the current interface ? Example:
interface bar(T)
{
void method1(T a);
void method2(T a);
}
interface baz: bar!int
{
final void method1(int a){}
}
class foo: baz
{
this(){method1(0);}
void method2(int a){}
}
void main()
{
auto Foo = new foo;
Foo.method2(0);
}
outputs:
myfile.d(xx): Error: foo interface function 'void method1(int a)'
is not implemented
It seems that the compiler doesnt get that baz.method1 is actually bar.method1.
Note that the example illustrates that in baz, for some reasons, we know that method1 will always have the same implemtation. a baz implementer mays be down-casted as a bar (so making a dummy final method1 in bar is not possible).
Interfaces can only declare virtual members without implementation, or final members with implementation. Your code is attempting to override a virtual method with a non-virtual implementation. Due to the nature of interfaces, you cannot actually override anything within them. What you want instead is an abstract class.
abstract class baz: bar!int
{
override void method1(int a){}
}
Replacing your baz interface with the above class will clear up the issue.
As an example of why this isn't allowed, consider this code: (Does not compile, of course!)
interface Root {
int foo();
}
interface BranchA : Root {
override int foo() { return 1; }
}
interface BranchB : Root {
override int foo() { return 2; }
}
class C : BranchA, BranchB { }
What would (new C()).foo() return? The result is ambiguous. It is only acceptable to override the interface methods in a class, because unlike interfaces, you can only inherit one class at a time.

Should I use an interface or factory (and interface) for a cross-platform implementation?

Example A:
// pseudo code
interface IFoo {
void bar();
}
class FooPlatformA : IFoo {
void bar() { /* ... */ }
}
class FooPlatformB : IFoo {
void bar() { /* ... */ }
}
class Foo : IFoo {
IFoo m_foo;
public Foo() {
if (detectPlatformA()} {
m_foo = new FooPlatformA();
} else {
m_foo = new FooPlatformB();
}
}
// wrapper function - downside is we'd have to create one
// of these for each function, which doesn't seem right.
void bar() {
m_foo.bar();
}
}
Main() {
Foo foo = new Foo();
foo.bar();
}
Example B:
// pseudo code
interface IFoo {
void bar();
}
class FooPlatformA : IFoo {
void bar() { /* ... */ }
}
class FooPlatformB : IFoo {
void bar() { /* ... */ }
}
class FooFactory {
IFoo newFoo() {
if (detectPlatformA()} {
return new FooPlatformA();
} else {
return new FooPlatformB();
}
}
}
Main() {
FooFactory factory = new FooFactory();
IFoo foo = factory.newFoo();
foo.bar();
}
Which is the better option, example A, B, neither, or "it depends"?
I would say that your explicit factory option (option B) is generally better.
In your first example your Foo class is effectively doing two jobs, it's a factory and it's a proxy. Two jobs, one class, makes me uneasy.
Your second option puts a little more responsibility on the client: they need to know to use the factory, but this is such a widely used idiom that I think it's not hard to understand.
The problem with A is that you have to implement every method of IFoo in Foo. That is not a big deal if there are only a couple, but is a pain if there are dozens of them. If you are working with a language that supports factory methods, such as Curl, then you could put a factory method in IFoo:
{define-class abstract IFoo
{method abstract {bar}:void}
{factory {default}:{this-class}
{if platformA? then
{return {FooPlatformA}}
else
{return {FooPlatformB}}
}
}
}
{define-class FooPlatformA {inherits IFoo}
{method {bar}:void}
}
...
def foo = {IFoo}
{foo.bar}
If you ask me B is way better - since Foo itself does not need to do any switching on platform. Why does that matter? Well, since you probably want to test all components separately - Foo with a 'test' IFoo, FooPlatformA separately on platform A and FooPlatformB on platform B. If you stick the choice inside Foo you need to test Foo on both A and B, not only the different IFoos. Makes the components more coupled for no apparent reason.
The factory is a cleaner solution as you do not have implement each member of the interface in the wrapper class Foo : IFoo. Imagine, each time you modify the IFoo interface you would need update the wrapper. When programming, depending on your goals, try to consider maintainability as much as possible.
Are all 'platforms' available or only one of them? Is the only difference between the platforms is logic? Thinking from a game developer perspective I would use #defines to implement this.
class Platform : IPlatform
{
void Update()
{
#if PLATFORM_A
* ... Logic for platform A */
#elif PLATFORM_B
* ... Logic for platform A */
#endif
}
}
HTH,
Interfaces are used when it is possible that multiple implementations of a single functional set may exist. This sounds as though it applies to your particular scenario.
In terms of your examples, I would definitely roll with B, it is easier to maintain. A embeds too much common logic [ie platform detection] within individual classes [and/or methods]. If you are to build your own Factory class, try to generalize it [through a generic Resolve<IType> () method or something], as opposed to a method\class per interface.
For instance,
// i called it a "container" because it "contains" implementations
// or instantiation methods for requested types - but it *is* a
// factory.
public class Container
{
// "resolves" correct implementation for a requested type.
public IType Resolve<IType> ()
{
IType typed = default (IType);
if (isPlatformA)
{
// switch or function map on IType for correct
// platform A implementation
}
else if (isPlatformB)
{
// switch or function map on IType for correct
// platform B implementation
}
else
{
// throw NotSupportedException
}
return typed;
}
}
However, rather than implement your own Factory pattern, you may wish to investigate alternative implementations, such as MS's Unity2.0 or Castle Windsor's CastleWindsorContainer. These are easy to configure and consume.
Ideally,
// use an interface to isolate *your* code from actual
// implementation, which could change depending on your needs,
// for instance if you "roll your own" or switch between Unity,
// Castle Windsor, or some other vendor
public interface IContainer
{
IType Resolve<IType> ();
}
// custom "roll your own" container, similar to above,
public class Container : IContainer { }
// delegates to an instance of a Unity container,
public class UnityContainer : IContainer { }
// delegates to an instance of a CastleWindsorContainer,
public class CastleWindsorContainer : IContainer { }
Oh, suppose I ought to shout out to Ninject and StructureMap too. I am just not as familiar with these as with Unity or CastleWindsor.