abstract class methods overriding the methods of another abstract class - oop

Lets say that I have this line of code:
public abstract class User
{
public string name;
public string email;
public string password;
public abstract void Create();
public abstract void Remove();
public abstract void Modify();
}
And then another abstract class:
public abstract class AbstractCustomer : User
{
public string address;
public Order order;
public abstract override void Create(string n,string e,string pa,int ph,string a);
public abstract override void Modify(string e, string pa, int ph, string a);
public abstract override void Remove(Order o);
public abstract void PlaceOrder(Item i);
public abstract void MakePayment(Order o);
}
and we have the customer which implements the AbstractCustomer:
public class Customer : AbstractCustomer
{
public override void Create(string name, string email, string password, int phoneNum, string address)
{
this.name = name;
this.email = email;
this.password = password;
this.phoneNum = phoneNum;
this.address = address;
this.isActive = true;
ConnectionToDB.SaveCustToDB();
}
public override void Remove(Order order)
{
order.CancelOrder();
}
public override void Modify(string email, string password, int phoneNum, string address)
{
ConnectionToDB.UpdateCustInDB();
}
public override void PlaceOrder(Item item)
{
order = new Order(item);
}
public override void MakePayment(Order order)
{
ConnectionToDB.SavePayToDB(order);
}
}
and this is where the problem starts (this is a helper class whose purpose is to call the methods easily)
public static void Create(AbstractCustomer user, string name, string email, string password, int phoneNum, string address)
{
user.Create(name, email, password, phoneNum, address);
}
public static void Remove(AbstractCustomer user, Order order)
{
user.Remove(order);
}
public static void Modify(AbstractCustomer user, string email, string password, int phoneNum, string address)
{
user.Modify(email, password, phoneNum, address);
}
public static void PlaceOrder(AbstractCustomer user, Item item)
{
user.PlaceOrder(item);
}
public static void MakePayment(AbstractCustomer user, Order order)
{
user.MakePayment(order);
}
These lines of codes produces errors like:
VS will tell you that the Customer class didn't implement the User's abstract methods(well, I think I did because I tried overriding it in the AbstractCustomer). But apparently, we don't need to override it in the Abstract class because the child class(Customer) will automatically inherits it and from there you can just directly override the methods. I found the explanation here overriding abstract methods in an inherited abstract class
But by doing the above solution, it presents another problem. The AbstractCustomer class will lose its purpose and therefore the HelperClass can't call any methods because its static classes depends on the AbstractCustomer that will be passed in the method.
So for the questions: (Problem: Grouping the methods into a static class for me to call it easily)
Is there a way to fix this kind of problem?(I'm thinking of using decorator pattern)
If I use the decorator pattern, what is the purpose of the ConcreteComponent?Is it okay if I remove it?
If I don't use the decorator pattern, is there any pattern available for this kind of problem?
If I don't use any pattern, is there any way to solve this?
Thanks for reading! Sorry coz its a long one! :)

Your solution is not related to Decorator pattern. Decorator - it is something, that should be inherited from existing abstraction (AbstractCustomer in your case) and add extra logic to it (it can be logging, or it can be extra check of each method's parameters for null, or something like that...). See this link.
Btw, I don't like the way how you construct your abstractions. It is better to have well-grained interfaces for each of your methods, e.g. ICanCreate for Create() method, ICanRemove for Remove() method, etc. It allows you to control further types which will implement that functionality. E.g., one customer can implement only ICanCreate interface, another one - ICanCreate + ICanRemove, etc.

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.

Can I refer to properties directly in entity constructor with EclipseLink?

EclipseLink version is 2.5.1
We've moved from GlassFish web-server to TomCat. This made us switch to static weaving because with TomCat dynamic weaving doesn't really work that easy.
Now that static weaving works, it seems to work quite a bit differently.
If I have an entity which sets some property directly in the constructor:
class Entity {
#Column
private String name;
public Entity() {
name = "something";
}
public String getName() {
return name;
}
}
Long story short this test will fail:
Entity e = new Entity();
assertEquals("something", e.getName()); // e.getName() returns null
This happens because getName(), after weaving, is not returning this.name anymore. Instead it calls a routing for initialization (if it's needed) and (I guess) gets the value of the property from some underlying HashMap.
But constructor is not being weaved, I even have looked into the sources of weaver and seems to be explicitly opting out of this:
/**
* Construct a MethodWeaver and allow it to process the method.
*/
#Override
public MethodVisitor visitMethod(int access, String methodName, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, methodName, desc, signature, exceptions);
if (!alreadyWeaved) {
// skip constructors, they will not changed
if (!"<init>".equals(methodName) && !"<cinit>".equals(methodName)) {
// remaining modifications to the 'body' of the class are
// delegated to MethodWeaver
mv = new MethodWeaver(this, methodName, desc, mv);
}
}
return mv;
}
The question is, maybe I miss something here? Is it the actual reality with EclipseLink 2.5.1 that you can't use properties directly in entity's own ctor? (and it's not even mentioned anywhere, not googlable at least)
It turns out yes, we can.
But there was a problem that led us to the property being not visible to the getter.
We actually have MappedSuperclass inheritance here and we were shadowing this field in the child class. Essentially this:
class A {
#Column()
protected String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class B extends A {
#Column()
protected String name;
// no #Override here
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
So we were just shadowing the property.

Jackson JSON serialization of JPA Entities

I have a JPA persistence layer with many #Entity classes which have many OneToMany and ManyToMany relationships.
I want to expose that entities by RestEasy with Jackson2 as serializer to JSON as REST services.
I know about #JsonIdentityInfo for resolving circular references.
The problem is in different REST services I need to expose different subsets of Entity fields. Moreover I need to expose different levels of depts for collections (OneToMany, OneToOne etc).
For example for this simple Entities:
class User {
Long id;
String name;
Company company;
}
class Company {
Long id;
String name;
List<User> users;
List<Product> products;
}
class Product {
Long id;
String name;
List<User> users;
}
and this REST service:
class MyResource {
User getUser() { //... }
List<User> getUsers() { //... }
Company getCompany() { //... }
List<Company> getComanies() { //... }
}
In method getUser() I need to return JSON with full User object including inner Company object. But that company of course only need to include their id and name field and not full list of users. Even more important that inner Company JSON must not include products! It is logical. If we get the user we don't need products of company that related to this user. If we need them we will send another REST request.
But in method getCompany() I need to return JSON with full Company object including inner JSON arrays of User and Product objects. Of course this time that User objects doesn't need to include inner JSON for Company object.
For this reason I can't use #JsonIgnore. In one case we need some field and in another we doesn't.
Now I came up with approach of using Jackson views (#JsonView annotation). I have View class with different views for every MyResource getter.
public class Views {
public static class User {}
public static class Users {}
public static class Company {}
public static class Companies {}
// etc...
}
and MyResoruce class as
class MyResource {
#JsonView(Views.User.class)
User getUser() { //... }
#JsonView(Views.Users.class)
List<User> getUsers() { //... }
#JsonView(Views.Company.class)
Company getCompany() { //... }
#JsonView(Views.Companies.class)
List<Company> getComanies() { //... }
}
and have a MixIn classes for every Entity with every field annotated as
public abstract class UserMixIn {
#JsonView({ Views.User.class, Views.Users.class, Views.Company.class, Views.Companies.class })
public abstract Long getId();
#JsonView({ Views.User.class, Views.Users.class, Views.Company.class, Views.Companies.class })
public abstract String getName();
#JsonView({ Views.User.class, Views.Users.class })
public abstract Company getCompany();
}
public abstract class CompanyMixIn {
#JsonView({ Views.Company.class, Views.Companies.class, Views.User.class, Views.Users.class })
public abstract Long getId();
#JsonView({ Views.Company.class, Views.Companies.class, Views.User.class, Views.Users.class })
public abstract String getName();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract List<User> getUsers();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract List<Product> getProducts();
}
public abstract class ProductMixIn {
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract Long getId();
#JsonView({ Views.Company.class, Views.Companies.class })
public abstract String getName();
public abstract List<User> getUsers();
}
Plurals for support cases where getUsers() doesn't need full inner Company object for every user (performance).
Of course there are just example classes. Real classes are much bigger and complex.
I do not like this approach because I am afraid that in the future it can be a nightmare (too many not manageable views). Maybe there are common approach for exposing JPA Entities as REST services? I believe it is a fairly common task. But can not find any intelligible information on how others doing this. Maybe some best practices.
Your service layer (and your REST controller layer) must expose DTOs (Data transfer objects) instead of #Entity objects.
Example :
For a Service 1 (which focus on User managment) :
public class UserDto {
private Long id;
private String name;
private CompanyDtoLight company;
}
public class CompanyDtoLight {
private Long id;
private String name;
}
For a Service 2 (which focus on Company managment) :
public class CompanyDto {
private Long id;
private String name;
List<UserDtoLight > users;
List<ProductDtoLight > products;
}
public class UserDtoLight {
private Long id;
private String name;
}
class ProductDtoLight {
private Long id;
private String name;
}
(The naming of your DTOs is yours)
How to :
You will need Mappers to transfom and reverse your #Entity to DTOs. Some lib exist like Dozer or MapStruct (there are plenty of other).

OO polymorphism design

What is the best way to do the following:
Suppose I have a class called Person and many derived classes for specialized persons.
Suppose at the beginning of my app, I know I have to deal with a person but I won't know what kind of person it is until much later (something beyond my control so I cannot determine the Person type at the beginning).
So at the beginning I will create a Person and fill in attributes for it. Later, when I know what kind of Person it is, I would instantiate a specialized person and copy over the any saved attributes for her.
Is there a more elegant way to do this without creating two objects?
If you don't know the type of person up front, you won't be able to avoid instantiating two objects. There has to be something to contain the base Person attributes before you know the specialized person, but you can't take advantage of polymorphism without instantiating the specialized object later.
One option is to use a composition pattern, in which each specialized person contains a Person instance rather than inheriting from it. You still have to instantiate two objects, but you don't have to rewrite the code to copy over the saved attributes every time. Here's an example (C# syntax):
public interface IPerson
{
string Name { get; }
int Age { get; }
}
public class Person : IPerson
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public abstract class SpecialPersonBase : IPerson
{
private IPerson myPerson;
protected SpecialPersonBase(IPerson person)
{
myPerson = person;
}
public string Name { get { return myPerson.Name; } }
public int Age { get { return myPerson.Age; } }
public abstract string Greet();
}
public class Doctor : SpecialPersonBase
{
public Doctor(IPerson person) : base(person) { }
public override string Greet()
{
return "How are you feeling?";
}
}
public class Accountant : SpecialPersonBase
{
public Accountant(IPerson person) : base(person) { }
public override string Greet()
{
return "How are your finances?";
}
}
You could use the classes like this:
IPerson bob = new Person("Bob", "25");
// Do things with the generic object
// until you can determine the specific type
SpecialPerson specialBob;
if (bobIsDoctor)
{
specialBob = new Doctor(bob);
}
else if (bobisAccountant)
{
specialBob = new Accountant(bob);
}
specialBob.Greet();

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.