Base class or Abstract class without abstract method - oop

I have a problem to chose the between an abstract class without abstract methods OR a base class with an interface.
I have two implementation in my mind:
1.
Let's say I have a AbstractRenderer:
abstract class AbstractRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->asArray();
}
}
and the WebRenderer would be like this:
class WebRenderer extends AbstractRenderer
{
}
2.
Have a base class and an interface like this:
Interface InterfaceRenderer
{
public function __construct(AbstractShape $shape);
public function render(): string;
}
and a base class that impediments the interface:
class BaseRenderer implements InterfaceRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->toString();
}
}
again, my WebRenderer would be like this:
class WebRenderer extends BaseRenderer
{
}
I don't know which is the correct implementation, or there is a better way to implement this and what is the pros and cons of each.
Thanks

From the Renderer client’s perspective the 2 solutions are basically identical. As long as they depend on an abstract object (interface or an abstract class), you’ll have benefits of polymorphism. You’d lose those if you make them depend on WebRenderer (concrete object).
Interface’s benefits over abstract classes
doesn’t occupy inheritance
no fragile base class problem
Abstract classes provide
static methods (in many languages interface can’t have these)
protected implementation

Related

using default and statics methods in interfaces

We use abstract classes if we need to keep an implemented method and method definitions while we use interfaces if we need to keep just the method definitions. But in java and C# we can use default methods and static methods to include implementations in interfaces. So what is the use of abstract classes if we can achieve what it is intended to do by using interfaces?
There are some reasons to have abstract classes.
Abstract classes can inherit interfaces, but not vice versa
Abstract classes can inherit interfaces. However, interface cannot inherit abstract class:
public interface ABar { }
public abstract class Bar : IFoo { }
However, this is not eligible:
public interface IFoo : ABar
{
}
public abstract class ABar
{
}
Abstract classes can have constructors, fields (can hold state)
Abstract classes can have constructors, fields. By having fields, it is possible to hold state. However, interface cannot have them.
public abstract class ABar
{
public int test; // some state
public ABar()
{
}
}

Implement optional functions in an abstract class

In Kotlin I have an abstract class that other classes can inherit from. I would like to have some functions that the class that inherits this class can optionally implement. In the code below, the function is protected abstract. This however requires that the class that is inheriting this class MUST implement these functions. Is there a way to make it so that the class that is inheriting can choose to implement the functions or not implement them?
abstract class BaseDialogFragment {
protected abstract fun getButton1Text(): String
protected abstract fun getButton2Text(): String
}
It is very simple, you just provide the default implementation like in the example below and your inheritors can override them:
abstract class BaseDialogFragment {
open fun getButton1Text(): String {
TODO("Your default implementation here")
}
open fun getButton2Text(): String {
TODO("Your default implementation here")
}
}

UML class diagram relation with mother class if every child class uses the same thing

I have two questions:
I have a Singleton class with a property Layout that I use in creating child objects of an abstract class (example below). The abstract class has an abstract method where the layout file is given as a variable. Do I connect that Singleton class to the abstract class or each child? The following example is written using pseudo-code:
public class SingletonClass
{
public static Instance;
public var[,] Layout;
}
public abstract class AbstractClass
{
public abstract void DoSomething(var[,] Layout);
}
public class ClassA : AbstractClass
{
public override void DoSomething(var[,] Layout) { some code }
}
public class ClassB : AbstractClass
{
public override void DoSomething(var[,] Layout) { some other code }
}
Is it even needed, or "cleaner", to give the Layout as variable in the method, or is it ok to just call Layout from the singleton class?
The following UML is an equivalent of your code
under the following assumptions: Instance and Layout are assumed to be attributes of analogous classes.
SingletonClass has two owned attributes (denoted by the big dots): public layout of type Layout and instance of type AbstractClass (it's abstract, hence the italics). The latter will later hold either an instance of the concrete ClassA or ClassB.
Whether or not the design is ok depends. Basically there's nothing wrong with this.

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

Jackson mixin selection and inheritance

I have a problem with Jackson mixin and inheritance. I have two target classes, a parent and a child. For those two target classes I have defined two MixIn classes (interfaces) with no inheritance relationship with each other. I also tested with one MixIn interface extending the other but there was no difference in the outcome. When Jackson serializes the parent class it uses the correctly defined mixin for the serialization config and everything works well. However when Jackson serializes the child class it will use the parent class mixin definitions for serializing properties that exist in both the parent and the child class. Then it uses the child class mixin definitions for serializing the properties defined in the child class but not in the parent class. Now this probably has something to do with comparing the base classes or implementing interfaces in Jackson.
Now the question is that is there any way that I could instruct Jackson to use only the mixin definitions for the child class when serializing objects of the child class? And yes I would like to keep both the the mixin definitions in place for two separate use cases so just removing the parent class mixin mapping is not gonna solve my issue.
Example code and expected and actual output JSONs below.
Environment:
Jackson version 2.1.4
Tomcat version 7.0.34.0
Target classes and interfaces they implement:
public interface TestI {
public String getName();
}
public interface TestExtendI extends TestI {
public Integer getAge();
}
public class Test implements TestI {
String name;
public Test(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public class TestExtend extends Test implements TestExtendI {
private Integer age;
public TestExtend(String name) {
super(name);
}
public TestExtend(String name, Integer age) {
super(name);
this.age = age;
}
#Override
public Integer getAge() {
return age;
}
}
Mixins definitions
public interface TestMixIn {
#JsonProperty("base-name")
public String getName();
}
public interface TestExtendMixIn {
#JsonProperty("ext-name")
public String getName();
#JsonProperty("ext-age")
public Integer getAge();
}
If both mixins are added to the mapper the output JSON is:
{
"base-name": "5", // from parent class mixin definition
"ext-age": 50 // from child class mixin defition
}
With mixin for TestI.class commented everything works as expected and the output JSON is (this is what I would like to achieve):
{
"ext-name": "5", // from child class mixin defition
"ext-age": 50 // from child class mixin defition
}
Object mapper configuration
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JacksonObjectMapper() {
mapper = new ObjectMapper();
mapper.addMixInAnnotations(TestI.class, TestMixIn.class);
mapper.addMixInAnnotations(TestExtendI.class, TestExtendMixIn.class);
}
public ObjectMapper getContext(Class<?> type) {
return this.mapper;
}
}
REST api for handling the request/response
#Path("api/test/{id}")
public class TestRestApi {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public TestI getTest(#PathParam("id") String id) {
TestI ret = new TestExtend(id, 50);
return ret;
}
}
Solution
As described by pgelinas in the first response the solution to this problem is to define the methods that should be handled by the 'child' mixin again in the child interface. For the example code above that would mean changes to the TestExtendI interface:
public interface TestExtendI extends TestI {
public Integer getAge();
// override the method from the parent interface here
#Override
public String getName();
}
This will solve the issue and doesn't add too much boilerplate code to the solution. Moreover it will not change the interface contracts since the child interface already extends the parent interface.
This is a tricky one; the answer to your specific question is no, you cannot tell a child class to not use the Mixin applied to a parent class.
However, a simple solution to your problem here is to re-declare the getName() method in the TestExtendI interface. I believe MixIn annotation resolution doesn't follow the usual parent-child override (as is the case with normal annotations), but will instead prefer the MixIn that is applied to the class that declares the method. This might be a bug in Jackson or a design choice, you can always fill an issue on github.