How To Create Interface That Uses the Class that Extends It - c++-cli

I'm writing some hypothetical code for practice, and I came across a design issue.
Suppose that I have a class GameObject:
public ref class GameObject : GameObjectBluePrint {
public:
property double health;
property double damage;
property double defense;
property double strideLength;
property System::Drawing::Point location;
public:
virtual void Attack(GameObject% enemy) {
enemy.health -= this->damage;
}
virtual void Defend(GameObject% enemy) {
this->health -= enemy.damage * 0.5;
}
virtual void Move(Direction direction) {
switch (direction) {
case Direction::up:
this->location.Y += this->strideLength;
break;
case Direction::down:
this->location.Y -= this->strideLength;;
break;
case Direction::right:
this->location.X += this->strideLength;;
break;
case Direction::left:
this->location.X -= this->strideLength;
break;
}
}
virtual bool isVisible(GameObject% otherObject) {
double distance = Math::Sqrt(Math::Pow(this->location.X - otherObject.location.X, 2) + Math::Pow(this->location.Y - otherObject.location.Y, 2));
return distance <= 2;
}
};
And I want to make different types of these objects, so I create an interface that this class extends:
public interface class GameObjectBluePrint {
void Attack(GameObject% enemy);
void Defend(GameObject% enemy);
void Move(Direction direction);
bool isVisible(GameObject% otherObject);
};
The issue is that this interface relies on the GameObject class being defined first. However, for the GameObject class to be defined, I have to extend this interface. Am I going about this interface concept incorrectly, or is there a way to avoid nested messes like this one?

How about combine the https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
https://msdn.microsoft.com/de-de/library/2kb28261.aspx
generic <typename TGameObject>
public interface class class GameObjectBluePrint {
void Attack(TGameObject% enemy);
void Defend(TGameObject% enemy);
void Move(Direction direction);
bool isVisible(TGameObject% otherObject);
};
public ref class GameObject : GameObjectBluePrint<GameObject> {
...
}

Related

Is it ok to override a virtual method but provide no implementation?

I'm trying to create a class heirachy for a game, there is an Item class which is the base class for all items in the game. The problem is that some derived items (like potion) might not implement some of the abstract methods defined by the item.
Is it ok for derived classes to implement an abstract method with "do nothing"?
Example: https://dotnetfiddle.net/jJABN1
using System;
using System.Collections.Generic;
public abstract class Item
{
public abstract void Use();
}
public class Potion : Item
{
public override void Use()
{
// do nothing
return;
}
}
public class Sword : Item
{
public override void Use()
{
Console.WriteLine("Sword used!");
return;
}
}
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>();
Item potion = new Potion();
Item sword = new Sword();
items.Add(potion);
items.Add(sword);
for (int i = 0; i < items.Count; i++)
{
Item item = items[i];
item.Use();
}
}
}
One of Robert Martin's SOLID Principles - Interface Segregation Principle addresses this situation. It basically says that a client should not be exposed to methods it doesn't need.
An example of violating the Interface Segregation Principle:
// Abstraction
public abstract class Printer
{
public abstract void Print();
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
// Basic printers can't scan
}
}
This is usually solved by separating an abstract class to multiple smaller abstract classes that can optionally inherit one other:
// Abstractions
public abstract class Printer
{
public abstract void Print();
}
public abstract class AllInOnePrinter : Printer
{
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : AllInOnePrinter
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
}
Technically, there could be an edge-case (should be uncommon!) where a deriving class doesn't need to implement all the methods, in such a case I'd rather it to override and throw an error to signal the user that this method should not be used.
That said, in the provided example there is only one method, so the question is: if a derived class doesn't need this method - why do you need to inherit the abstract class to begin with? if it's just in order to provide an example that's understandable - but better improve the example to include other methods that are used in the derived class.

Interface Segregation Principle- Program to an interface

I was reading about SOLID and other design principles. I thought ISP was the same as "Program to an interface, not an implementation". But it looks like these are different principles?
Is there a difference?
Robert Martin has a very good explanation of Interface segregation principle (ISP), in his book "UML for Java Programmers". Based on that, I don't think ISP is about an interface being "focused" on one logical, coherent group of things. Because, that goes without saying; or, at least it should go without saying. Each class, interface or abstract class should be designed that way.
So, what is ISP? Let me explain it with an example. Say, you have a class A and a class B, which is the client of class A. Suppose, class A has ten methods, of which only two are used by B. Now, does B need to know about all ten methods of A? Probably not - the principle of Information hiding. The more you expose, the more you create the chance for coupling. For that reason, you may insert an interface, call it C, between the two classes (segregation). That interface will only declare the two methods that are used by B, and B will depend on that Interface, instead of directly on A.
So now,
class A {
method1()
method2()
// more methods
method10()
}
class B {
A a = new A()
}
will become
interface C {
method1()
method2()
}
class A implements C{
method1()
method2()
// more methods
method10()
}
class B {
C c = new A()
}
This, prevents B from knowing more than it should.
ISP is focused on the idea of each interface representing one discrete and cohesive behavior.
That is, each logical group of things an object should do would map to a single specific interface. A class might want to do several things, but each thing would map to a specific interface representing that behavior. The idea is each interface is very focused.
Assume that you have one fat interface with many methods to be implemented.
Any class, that implements that fat interface has to provide implementation for all these methods. Some of the methods may not be applicable to that concrete class. But still it has to provide implementation in absence of interface segregation principle.
Let's have a look at example code in absence of Interface segregation.
interface Shape{
public int getLength();
public int getWidth();
public int getRadius();
public double getArea();
}
class Rectangle implements Shape{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Shape{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Shape{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceNoSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
output:
java InterfaceNoSeggration
Rectangle area:200.0
Square area:225.0
Circle area:12.56
Notes:
Shape is a general purpose fat interface, which contains methods required for all Shape implementations like Rectangle, Circle and Square. But only some methods are needed in respective Shape childs
Rectangle : getLength(), getWidth(), getArea()
Square : getLength() and getArea()
Circle : getRadius() and getArea()
In absence of segregation, all Shapes have implemented entire fat interface : Shape.
We can achieve same output with interface segregation principle if we change the code as follows.
interface Length{
public int getLength();
}
interface Width{
public int getWidth();
}
interface Radius{
public int getRadius();
}
interface Area {
public double getArea();
}
class Rectangle implements Length,Width,Area{
int length;
int width;
public Rectangle(int length, int width){
this.length = length;
this.width = width;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return width * length;
}
}
class Square implements Length,Area{
int length;
public Square(int length){
this.length = length;
}
public int getLength(){
return length;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
// Not applicable
return 0;
}
public double getArea(){
return length * length;
}
}
class Circle implements Radius,Area{
int radius;
public Circle(int radius){
this.radius = radius;
}
public int getLength(){
// Not applicable
return 0;
}
public int getWidth(){
// Not applicable
return 0;
}
public int getRadius(){
return radius;
}
public double getArea(){
return 3.14* radius * radius;
}
}
public class InterfaceSeggration{
public static void main(String args[]){
Rectangle r = new Rectangle(10,20);
Square s = new Square(15);
Circle c = new Circle(2);
System.out.println("Rectangle area:"+r.getArea());
System.out.println("Square area:"+s.getArea());
System.out.println("Circle area:"+c.getArea());
}
}
Notes:
Now individual Shapes like Rectangle, Square and Circle have implemented only required interfaces and got rid of un-used methods.
Agree with both the answers above. Just to give an example of TrueWill's code smell above, you shouldn't find yourself doing this:
#Override
public void foo() {
//Not used: just needed to implement interface
}
IWorker Interface:
public interface IWorker {
public void work();
public void eat();
}
Developer Class :
public class Developer implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("Developer working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("developer eating");
}
}
Robot Class:
public class Robot implements IWorker {
#Override
public void work() {
// TODO Auto-generated method stub
System.out.println("robot is working");
}
#Override
public void eat() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("cannot eat");
}
}
For a more complete example go here.
Here's a real-world example of this principle (in PHP)
Problem Statement:
I want various forms of content to have comments/discussion associated with them. That content might be anything from a forum topic, to a news article, to a user's profile, to a conversation-style private message.
Architecture
We will want a re-usable DiscussionManager class which attaches a Discussion to a given content entity. However, the above four examples (and many more) are all conceptually different. If we want the DiscussionManager to use them, then all four+ need to have one common interface that they all share. There is no other way for DiscussionManager to use them unless you want to your arguments to go naked (e.g. no type checking).
Solution: Discussable interface with these methods:
attachDiscussion($topic_id)
detachDiscussion()
getDiscussionID()
Then DiscussionManager might look like this:
class DiscussionManager
{
public function addDiscussionToContent(Discussable $Content)
{
$Discussion = $this->DiscussionFactory->make( ...some data...);
$Discussion->save() // Or $this->DiscussionRepository->save($Discussion);
$Content->attachDiscussion($Discussion->getID()); // Maybe saves itself, or you can save through a repository
}
public function deleteDiscussion(Discussable $Content)
{
$id = $Content->getDiscussionID();
$Content->detatchDiscussion();
$this->DiscussionRepository->delete($id);
}
public function closeDiscussion($discussion_id) { ... }
}
This way, DiscussionManager does not care about any of the unrelated behaviors of the various content types that it uses. It ONLY cares about the behaviors it needs, regardless of what those behaviors are associated with. So by giving each content type that you want to have discussions for, a Discussable interface, you are using the interface segregation principle.
This is also a good example of a situation where an abstract base class is not a good idea. A forum topic, user profile, and news article aren't even remotely conceptually the same thing, thus trying to get them to inherit the discussion behaviors leads to strange coupling to an unrelated parent. Using a specific interface that represents discussions, you can makes sure that the entities you want to have discussions, are compatible with the client code that will be managing those discussions.
This example might also be a good candidate for usage of Traits in PHP, for what it's worth.

Adding State in Decorator Pattern

I wonder how to add state to the chain of decorators that will be available to the consumer. Given this simplified model:
abstract class AbstractPizza
{
public abstract print(...);
}
class Pizza : AbstractPizza
{
public int Size { get; set; }
public print(...);
}
abstract class AbstractPizzaDecorator
{
public Pizza:AbstractPizza;
public abstract print();
}
class HotPizzaDecorator : AbstractPizzaDecorator
{
public int Hotness { get; set; }
public print(...);
}
class CheesyPizzaDecorator : AbstractPizzaDecorator
{
public string Cheese { get; set; }
public print(...);
}
void Main()
{
BigPizza = new Pizza();
BigPizza.Size = 36;
HotBigPizza = new HotPizzaDecorator();
HotBigPizza.Pizza = BigPizza;
HotBigPizza.Hotness = 3;
HotBigCheesyPizza = new CheesyPizzaDecorator();
HotBigCheesyPizza.Pizza = HotBigPizza;
HotBigCheesyPizza.Cheese = "Blue";
HotBigCheesyPizza.print();
HotBigCheesyPizza.size = 28; // ERRRRRR !
}
Now if they all implement the print method and propagate that though the chain, it's all good. But how does that work for the state? I can't access the size property on the HotBigCheesyPizza.
What's the part that I'm missing? Wrong pattern?
Thanks for helping!
Cheers
The decorator pattern is for adding additional behavior to the decorated class without the client needing to adjust. Thus it is not intended for adding a new interface (e.g. hotness, cheese) to the thing being decorated.
A somewhat bad example of what it might be used for is where you want to change how size is calculated: you could create a MetricSizePizzaDecorator that converts the size to/from English/metric units. The client would not know the pizza has been decorated - it just calls getSize() and does whatever it needs to do with the result (for example, to calculate the price).
I would probably not use the decorator in my example, but the point is: it does not alter the interface. In fact, nearly all design patterns come down to that - adding variability to a design without changing interfaces.
one way of adding state is by using a self referential data structure (a list). but this uses the visitor pattern and does more than you probably want. this code is rewritten from A little Java, a few patterns
// a self referential data structure with different types of nodes
abstract class Pie
{
abstract Object accept(PieVisitor ask);
}
class Bottom extends Pie
{
Object accept(PieVisitor ask) { return ask.forBottom(this); }
public String toString() { return "crust"; }
}
class Topping extends Pie
{
Object topping;
Pie rest;
Topping(Object topping,Pie rest) { this.topping=topping; this.rest=rest; }
Object accept(PieVisitor ask) { return ask.forTopping(this); }
public String toString() { return topping+" "+rest.toString(); }
}
//a class to manage the data structure
interface PieManager
{
int addTopping(Object t);
int removeTopping(Object t);
int substituteTopping(Object n,Object o);
int occursTopping(Object o);
}
class APieManager implements PieManager
{
Pie p=new Bottom();
// note: any object that implements a rational version of equal() will work
public int addTopping(Object t)
{
p=new Topping(t,p);
return occursTopping(t);
}
public int removeTopping(Object t)
{
p=(Pie)p.accept(new RemoveVisitor(t));
return occursTopping(t);
}
public int substituteTopping(Object n,Object o)
{
p=(Pie)p.accept(new SubstituteVisitor(n,o));
return occursTopping(n);
}
public int occursTopping(Object o)
{
return ((Integer)p.accept(new OccursVisitor(o))).intValue();
}
public String toString() { return p.toString(); }
}
//these are the visitors
interface PieVisitor
{
Object forBottom(Bottom that);
Object forTopping(Topping that);
}
class OccursVisitor implements PieVisitor
{
Object a;
OccursVisitor(Object a) { this.a=a; }
public Object forBottom(Bottom that) { return new Integer(0); }
public Object forTopping(Topping that)
{
if(that.topping.equals(a))
return new Integer(((Integer)(that.rest.accept(this))).intValue()+1);
else return that.rest.accept(this);
}
}
class SubstituteVisitor implements PieVisitor
{
Object n,o;
SubstituteVisitor(Object n,Object o) { this.n=n; this.o=o; }
public Object forBottom(Bottom that) { return that; }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
that.topping=n;
that.rest.accept(this);
return that;
}
}
class RemoveVisitor implements PieVisitor
{
Object o;
RemoveVisitor(Object o) { this.o=o; }
public Object forBottom(Bottom that) { return new Bottom(); }
public Object forTopping(Topping that)
{
if(o.equals(that.topping))
return that.rest.accept(this);
else return new Topping(that.topping,(Pie)that.rest.accept(this));
}
}
public class TestVisitor
{
public static void main(String[] args)
{
// make a PieManager
PieManager pieManager=new APieManager();
// add some toppings
pieManager.addTopping(new Float(1.2));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("cheese"));
pieManager.addTopping(new String("onions"));
pieManager.addTopping(new String("peperoni"));
System.out.println("pieManager="+pieManager);
// substitute anchovies for onions
int n=pieManager.substituteTopping(new String("anchovies"),new String("onions"));
System.out.println(n+" pieManager="+pieManager);
// remove the 1.2's
n=pieManager.removeTopping(new Float(1.2));
System.out.println(n+" pieManager="+pieManager);
// how many anchovies do we have?
System.out.println(pieManager.occursTopping(new String("anchovies"))+" anchovies");
}
}
I believe your component Pizza and your abstract decorator PizzaDecorator are supposed to share the same interface, that way each instance of the decorator is capable of the same operations as the core component Pizza.

Overriding properties from abstract class in Salesforce Apex

I have an abstract class in apex with several properties that I would like to override in a child class. According to the documentation, properties support both the override and virtual access modifiers. However, when I try to use either of them in either the parent or child class, I get an error saying that variables cannot be marked as virtual/override. Here is a facsimile of the code that causes this error:
public abstract class Row{
public virtual double value{
get{return value==null ? 0 : value;}
set;
}
}
public class SummaryRow extends Row{
private list<Row> childRows;
public override double value{
get{
totalValue = 0;
for(Row childRow:childRows){
totalvalue += childRow.value;
}
return totalValue;
}
}
}
Is this functionality not supported, or is there something that I am missing?
Thanks in advance.
Unfortunately, as far as I know that is a mistake in the documentation. I've only been able to apply the override and virtual modifiers to methods. You can, of course, get the desired effect by manually writing your property getter/setter methods:
public abstract class TestRow {
public Double value;
public virtual Double getValue() {
return value==null ? 0 : value;
}
public void setValue(Double value) {
this.value = value;
}
}
public class SummaryTestRow extends TestRow {
private list<TestRow> childRows;
public override Double getValue() {
Double totalValue = 0;
for(TestRow childRow : childRows){
totalValue += childRow.value;
}
return totalValue;
}
}

Design: classes with same implementation but different method names

I have multiple classes that have similar implementation for different named methods:
class MyClassX
{
public int MyClassXIntMethod(){}
public string MyClassXStringMethod(){}
}
class MyClassY
{
public int MyClassYIntMethod(){}
public string MyClassYStringMethod(){}
}
the methods inside the classes have similar implementation but because the method's names are different (due to 3rd party constraints) i cannot use inheritance.
I'm looking for an elegant solution that would be better than implementing the same functionality over and over again.
The classic answer IMHO is use the adpater pattern for every 3rd party calling party.
Don't apply blindly but see if it is a good fit first.
class MyClassXAdapter
{
IMyInterface _myImpClass
public int MyClassXIntMethod(){ return _myImpClass.IntMethod()}
public string MyClassXStringMethod(){ return _myImpClass.StringMethod() }
}
class MyClassYAdapter
{
IMyInterface _myImpClass
public int MyClassYIntMethod(){ return _myImpClass.IntMethod()}
public string MyClassYStringMethod(){ _myImpClass.StringMethod() }
}
class MyClassImplementation :IMyInterface
{
public int IntMethod(){}
public string StringMethod(){}
}
And whats the problem in using composition?
class MyClassY
{
private MyClassX myclx;
public int MyClassYIntMethod()
{
return myclx.MyClassXIntMethod();
}
public string MyClassYStringMethod(){...Similarly here...}
}
Why not simply create a common super class, and let each "MyClass_" call that common function? You can have a different program signature and still reuse the same codes pieces. Without copy and paste the same code again.
class MyClassX extends MyClassGeneric
{
public int MyClassXIntMethod(){}
public string MyClassXStringMethod(){}
}
class MyClassY extends MyClassGeneric
{
public int MyClassYIntMethod(){ return MyClassIntMethod();}
public string MyClassYStringMethod(){return MyClassStringMethod();}
}
class MyClassGeneric
{
protected int MyClassIntMethod(){ /*...... logic .....*/ return 0; }
protected string MyClassStringMethod(){/*...... logic ....*/return "";}
}
Real world example.
Without "software patternitis". (I apply software patterns, very useful, but, I'm not adicted to them).
collections.hpp
#define pointer void*
class Collection {
protected:
VIRTUAL bool isEmpty();
VIRTUAL void Clear();
}
class ArrayBasedCollection: public Collection {
protected:
int internalInsertFirst(pointer Item);
int internalInsertLast(pointer Item);
pointer internalExtractFirst(int Index);
pointer internalExtractLast(int Index);
}
class Stack: public ArrayBasedCollection {
public:
OVERLOADED bool isEmpty();
OVERLOADED void Clear();
// calls protected "internalInsertFirt"
void Push(pointer Item);
// calls protected "internalExtractLast"
pointer Pop(pointer Item);
}
class Queue: public ArrayBasedCollection {
public:
OVERLOADED bool isEmpty();
OVERLOADED void Clear();
// calls protected "internalInsertFirt"
void Push(pointer Item);
// calls protected "internalExtractFirst"
pointer Pop(pointer Item);
}
Cheers.