DESIGN PATTERNS - Parsing 4 different JSON files - oop

I have a problem that I cannot figure out. I have 4 different JSON files for configurations. Some of these files require extra API calls whereas others don't for instance.
4 files
A
B
C
D
A and B just require.
A.getConfigs()
B.getConfigs()
C however requires
C.getConfigs()
C.getCase()
D requires
D.getConfigs()
D.getHeader()
What kind of pattern/object should I use when I also want to be able to call individual methods for C and D?
I could very easily move the getCase and getHeader logic into the client code but then I realized I need to use this logic in multiple places in the application code. So what can I do now?

You may be looking for the facade pattern, which aims provide a simplified interface to more complex operations.
I'm taking a bit of liberty here by calling it a facade, as it usually involves wrapping other classes, instead of merely implementing an interface, but I think it still applies.
/* define facade interface */
interface Configurable {
void configure();
}
/* abstract basic configuration */
abstract class Config
implements Configurable
{
abstract void getConfigs();
void configure() {
getConfigs();
}
}
/* implementations */
class ConfigA
extends Config
{
void getConfigs() {
/* do stuff */
}
}
class ConfigB
extends Config
{
void getConfigs() {
/* do stuff */
}
}
class ConfigC
extends Config
{
void getConfigs() {
/* do stuff */
}
void getCase() {
/* do stuff */
}
/* override configure */
void configure() {
getConfigs();
getCase();
}
}
class ConfigD
extends Config
{
void getConfigs() {
/* do stuff */
}
void getHeader() {
/* do stuff */
}
/* override configure */
void configure() {
getConfigs();
getHeader();
}
}
/* usage */
class Client
{
private Config config;
Client(Config config) {
this.config = config;
}
void start() {
config.configure();
/* do more stuff */
}
}
However, if, as your method names seem to imply, getConfigs(), getCase() and getHeader() should return values that the client needs to operate on then things could get a bit complicated and maybe this pattern doesn't add many benefits.
Also, I overlooked that you want to be able to individually call the methods of C and D, which is still possible with my suggestion, but if you didn't intend to execute them with getConfigs() at the same time at all then my idea is probably not what you are looking for.

Related

How to wrap a C++ library

I'm developing an application which is using a library and I would like to wrap this library so that it does not goes to deep into my application code. Thanks to that I could change the library I'm using just by re-implementing my wrapper classes.
Suppose that I have a library LibA. It gives me 2 objects to work with, LibAObj1 and LibAObj2. LibAObj2 has a method using LibAObj1.
Here can be a simple definition of their declaration
class LibAObj1 {};
class LibAObj2
{
void action(LibAObj1 &obj);
};
Now I would like to define an interface that my application can use to wrap those objects in my application code
For instance:
class ItfLibAObj1 {};
class ItfLibAObj2
{
public:
void action(ItfLibAObj1 &obj) = 0;
};
The problem comes whenever I want to implement my interface ItfLibAObj2.
class ImplLibAObj2 : public ItfLibAObj2
{
public:
void action(ItfLibAObj1 &itfObj)
{
<how to get my LibAObj1 from itfObj>?
obj.action(LibAObj1);
}
private:
LibObj2 obj;
}
The question is actually in the pseudo code. How to get my LibAObj1 contained in my ItfLibAObj1 reference? I could add a getter function in LibAObj1 interface to return a void pointer that I would cast but I don't find that elegant in C++.
Is there any kind of design pattern I could use to solve my problem? Or do I just have a design issue?
Note that I'm not wishing to select which library to use at run time.
Thanks a lot for your help.
Kind regards
You problem perfectly explains why in Proxy Pattern, both the Real and Proxy must implement the same interface:
And your code should look like this:
// interfaces
class ItfLibAObj1 {};
class ItfLibAObj2
{
public:
void action(ItfLibAObj1 &obj) = 0;
};
// real
class RealLibAObj1 : public ItfLibAObj1 {};
class RealLibAObj2 : public ItfLibAObj2
{
void action(ItfLibAObj1 &obj)
{
...
}
};
// proxy
class ProxyLibAObj1 : public ItfLibAObj1
{
private:
RealLibAObj1 real;
};
class ProxyLibAObj2 : public ItfLibAObj2
{
private:
RealLibAObj2 real;
void action(ItfLibAObj1 &obj)
{
// do something
real.action(obj); // delegate to the real
// do something
}
};
However, if the whole purpose of your "wrapping" is adding a new layer between your core/real and the outside (client), please consider the Facade Pattern which provides a simpler interface to the client, instead of merely mimic the classes/methods of the core.

Correct way to disable base class functionality

Say, I have class A with method M:
private void M()
{
Do1();
Do2();
}
class B extends A.
Problem: I need Do2() to not to be executed when calling from an instance of B.
I have a couple of ideas but not sure which do not break OOP and SOLID rules.
Make Do2 virtual.
class A
{
protected virtual void Do2()
{
// Do something
}
}
class B
{
protected override void Do2()
{
// Do nothing
}
}
This solution looks weird to me because I override a method to "do nothing", when overriding is needed to "do something instead of something" or "do something in addition to something".
Create bool protected flag property
class A
{
protected virtual NeedCallDo2
{
get { return true; }
}
private void M()
{
Do1();
if (NeedCallDo2)
{
Do2();
}
}
}
class B
{
protected override NeedCallDo2
{
get { return false; }
}
}
This solution is also not perfect but I have a control of execution flow and can decide whether to call Do2 or not.
Pass constructor flag parameter
class A
{
private bool needCallDo2;
protected A(bool needCallDo2 = true)
{
this.needCallDo2 = needCallDo2;
}
private void M()
{
Do1();
if (this.needCallDo2)
{
Do2();
}
}
}
class B
{
public B()
: base(false)
{
}
}
This is a trick question! Given the solid-principles tag, there is no correct way to disable base class functionality, since that would violate liskov-substitution, which is the L in SOLID.
You could move the execution logic into an execution strategy class where class B uses a different strategy implementation than class A.

Patterns for role-based behaviour

I'm involved in an application migration project. This application is supposed to execute some logic based on the current user role, so this snippets like this are everywhere in the code:
if ("Role1".equals(user.getUserRole())){
operationVersionForRole1();
} else if ("Role2".equals(user.getRole())){
operationVersionForRole2();
} else if ("Role3".equals(user.getRole())){
operationVersionForRole3();
}
There are about five roles and almost fifty operations, and some operations are very complex for some roles (almost 1000 lines of code) so that style of programming makes the source code messy and hard to follow. Is there any know design pattern that helps to organize source code in that situations? Nested "if-else" just doesn't feel right.
Isn't it a Abstract Factory that provides an interface for creating families of related or dependent objects without specifying their concrete class? Specified role will be an argument to create concrete implementation. And operationVersionForRoleX could be designed as different implementation or strategy of IOperation interface.
interface IOperation
{
void Execute();
}
class OperationVersionForRoleX : IOperation
{
public void Execute()
{
// …
}
}
string role = "roleX";
IOperation operation = operationFactory.Create(role);
operation.Execute();
Simmilar to what casablanca has answered.
I usually avoid business logic inside an enum since their job is just uniqueness and pretty much are inferior to classes in everything else.
public enum Role {
ROLE1 { public Actions getActions(){ return new Role1Actions() } },
ROLE2 { public Actions getActions(){ return new Role2Actions() } },
ROLE3 { public Actions getActions(){ return new Role3Actions() } };
}
I would make the Actions interface with as many method as types of operations can be executed per role
public interface Actions {
void action1();
// useful when there are more than 1 different actions per role
// even if only 1 now, there will be more in the future
vpod action2();
}
Then, just use the actions you can get from roles
user.getUserRole().action1();
user.getUserRole().action2();
You could do something like this, where all operations extend the Operation superclass and Role is an actual object instead of a string:
public abstract class Operation {
public void execute(User user) {
user.getRole().apply(this);
}
public abstract void operationForRole1();
public abstract void operationForRole2();
public abstract void operationForRole3();
}
public enum Role {
ROLE1 { public void apply(Operation op) { op.operationForRole1(); } },
ROLE2 { public void apply(Operation op) { op.operationForRole2(); } },
ROLE3 { public void apply(Operation op) { op.operationForRole3(); } };
public abstract void apply(Operation op);
}
Each Operation then implements the logic for various roles, and the client simply calls operation.execute(user). No if-else anywhere.

Interface Bloated with Callbacks

Imagine the following class hierarchy:
interface IRules
{
void NotifyPickup(object pickedUp);
void NotifyDeath();
void NotifyDamage();
}
class CaptureTheFlag : IRules
{
public void NotifyPickup(Pickup pickedUp)
{
if(pickedUp is Flag)
GameOver();
}
public void NotifyDeath()
{
}
public void NotifyDamage()
{
}
}
class DeathMatch : IRules
{
public void NotifyPickup(Pickup pickedUp)
{
points++;
}
public void NotifyDeath()
{
lives--;
}
public void NotifyDamage()
{
}
}
class GameWorld
{
IRules gameMode;
public Main(IRules gameMode)
{
this.gameMode = gameMode;
}
object[] worldObjects;
public void GameLoop()
{
foreach(object obj in worldObjects)
{
// This call may have a bunch of sideeffects, like getting a pickup
// Or a player dying
// Or damage being taken
// Different game modes are interested in different events / statistics.
obj.Update();
// Stuff happens...
gameMode.NotifyDamage();
// Stuff happens...
gameMode.NotifyDeath();
}
}
}
So here I've got an interface which contains Notify* functions. These are callbacks. Different game modes are interested in different events of the game. It's not really possible to access the concrete objects creating these events because they're buried in the worldObjects array. Imagine we are adding new game modes to our game. The IRules interface will get hugely bloated, containing all the possible things a game mode may be interested in, and most calls will be stubbed! How can I prevent this?
Edit 2: Concrete example
Seems like your Process logic sends out a lot of events. If you would give these events a name, you could subscribe your observers to them.
Then it would even be possible to create a 'filtering' observer that can forward the events to any other observer (a decorator pattern):
struct Event {
enum e { A, B, /*...*/ };
e name;
};
class IEventListener {
public:
virtual void event( Event e ) = 0;
};
// an event dispatcher implementation:
using namespace std;
class EventDispatcher {
public:
typedef std::shared_ptr<IEventListener> IEventListenerPtr;
map<Event::e,vector<IEventListenerPtr>> listeners;
void event(Event e){
const vector<IEventListenerPtr> e_listeners=listeners[e.name].second;
//foreach(begin(e_listeners)
// ,end(e_listeners)
// ,bind(IEventListener::event,_1,e));
for(vector<IEventListenerPtr>::const_iterator it=e_listeners.begin()
; it!=e_listeners.end()
; ++it)
{
(*it)->event(e);
}
}
};
You program could look like this:
Main main;
EventEventDispatcher f1;
f1.listeners[Event::A].push_back(listener1);
main.listener=f1;
Note: code untested - grab the idea.
If you really want to decouple the sender from the sink, you put an event system in between. The example given here is very dedicated and lightweight, but do sure take a look at various existing implementations: Signals and Slots implemented in Qt and in Boost, the delegates from C#, ...
Apologizes if I missed something but why not use event? Basically let IController expose void Callback() method, then Main would be able subscribe any callback to own event:
class Main
{
private event EventHandler SomeEvent;
public Main(IController controller)
{
// use weak events to avoid memory leaks or
// implement IDisposable here and unsubscribe explicitly
this.SomeEvent += controller.Callback;
}
public void ProcessStuff()
{
// invoke event here
SomeEvent();
}
}
EDIT:
This is what I would do: extract each rule action into the separate interface so you just implement what you need in concrete classes, for instance CaptureTheFlag class does only PickupFlag action for now so does not need Damage/Death methods, so just mark by IPickupable and that's it. Then just check whether concrete instance supports concrete actions and proceed with execute.
interface IPickupable
{
void NotifyPickup(object pickedUp);
}
interface IDeathable
{
void NotifyDeath();
}
interface IDamagable
{
void NotifyDamage();
}
class CaptureTheFlag : IPickupable
{
public void NotifyPickup(Pickup pickedUp)
{
if (pickedUp is Flag)
GameOver();
}
}
class DeathMatch : IPickupable, IDeathable
{
public void NotifyPickup(Pickup pickedUp)
{
points++;
}
public void NotifyDeath()
{
lives--;
}
}
class GameWorld
{
public void GameLoop()
{
foreach(object obj in worldObjects)
{
obj.Update();
IPickupable pickupable = gameMode as IPickupable;
IDeathable deathable = gameMode as IDeathable;
IDamagable damagable = gameMode as IDamagable;
if (pickupable != null)
{
pickupable.NotifyPickup();
}
if (deathable != null)
{
deathable.NotifyDeath();
}
if (damagable != null)
{
damagable.NotifyDamage();
}
}
}
}
My final solution was the C# equivalent of what xtofl posted. I created a class which stored a bunch of delegates in it. These delegates started off with default values (so they would never be null) and the different concrete IRules classes could choose to overwrite them or not. This worked better than abstract or stubbed methods because it doesn't clog the interface with unrelated methods.
class GameEvents
{
public Action<Player> PlayerKilled = p => {};
public Func<Entity, bool> EntityValid = e => true;
public Action ItemPickedUp = () => {};
public Action FlagPickedUp = () => {};
}
class IRules
{
GameEvents Events { get; }
}
class CaptureTheFlag : IRules
{
GameEvents events = new GameEvents();
public GameEvents Events
{
get { return events; }
}
public CaptureTheFlag()
{
events.FlagPickedUp = FlagPickedUp;
}
public void FlagPickedUp()
{
score++;
}
}
Each rule set can choose which events it wants to listen to. The game simply calls then by doing Rules.Events.ItemPickedUp();. It's guaranteed never to be null.
Thanks to xtofl for the idea!

OO design problem

Suppose there's 2 classes : A and B.
A can operate on B.
I need to be able to query all B instances that A has operated on.
And for a specific B instance, I need to be able to query all A instances that have operated on it.
What's the elegant(in the OO taste..) solution for this kind of problem?
In a language like Java I would do something like:
package com.whatever.blah;
public class A {
private Set<B> patients = new HashSet<B>;
public void operateOn(B patient) {
patient.startRecoveringFromOperation(this);
patients.add(patient);
}
public List<B> getPatients() {
return patients;
}
}
public class B {
private Set<A> surgeons = new HashSet<A>;
//this has package access to `A` can access it but other classes can't
void startRecoveringFromOperation(A theSurgeon) {
surgeons.add(theSurgeon);
}
public List<A> getSurgeons() {
return surgeons;
}
}
This really isn't doing anything special, beyond using package access to allow A access to B's startRecoveringFromOperation() method while hiding the method from most other classes. In other languages you might use a different approach to accomplish this. For instance in C++ you might declare A as a friend of B instead.
import java.util.*;
class A {
void operate(B b) {
operatedOn.add(b);
b.operatedOnBy.add(this);
}
final Set<B> operatedOn = new HashSet<B>();
}
class B {
final Set<A> operatedOnBy = new HashSet<A>();
}
public class Main {
public static void main(String[] args) {
A a=new A();
B b=new B();
a.operate(b);
System.out.println(a+" "+a.operatedOn);
System.out.println(b+" "+b.operatedOnBy);
}
}