jeudi 1 août 2019

C++: Base class calling own virtual function - an anti-pattern?

I see pattern like below commonly used. We have a base class which does most of the work, but calls one of its own virtual/pure-virtual function to do the part of the job which is different for each derived type. A contrived example:

struct PacketProcessor {
    virtual void parseEncap(pkt) = 0;
    void process(Pkt pkt)
    {
        parseEncap(pkt);  // Calls its own virtual function to parse the encap
        processFurther(pkt);
        ...
    }
};

We create derived classes which will override the virtual functions and provide functionality specific to derived classes.

struct EthernetProcessor : public PacketProcessor {
    void parseEncap(Pkt) override { // parse ethernet encap}
};

struct PPPProcessor : public PacketProcessor {
     void parseEncap(Pkt) override { //parse ppp encap }
};

But I feel with this sort of pattern, as time goes on, more and more functions in the base class gets virtualized or more virtual function added and called at random places to make room for different derived class behavior.

[In a real life code I have see an add() and add_extra() virtual functions :-) ]

And over time the code does not have a solid structure any more as each type is handled in totally different ways. Even though the common base class sort of gives a false notion a structure. But yes it still keeps code for different types segregated as opposed to if (type1)/else(type2).

Another way of achieving something similar is to abstract out the differences into a different class (hierarchy) and call the virtual functions in that. This is also very common For Eg:

struct Encap {
    virtual void parseEncap(Pkt) = 0;
};

struct EthernetEncap : public Encap {
    void parseEncap(Pkt pkt) {}
};

struct PPPEncap : public Encap {
    void parseEncap(Pkt pkt) {}
};

struct PacketProcessor {
    PacketProcessor(Encap *encap) : m_encap{encap} {}
    void process(Pkt pkt)
    {
       m_encap->parseEncap(pkt);
       processFurther(pkt);
       ...
    }
private:
    EncapPtr m_encap;
};

But in this case also there can be frivolous functions added the Encap class. Or there will too many component classes like the Encap providing different functionality.

But the good thing is that the PacketProcessor will follow a specific path for all types of Encaps. Also this approach is not as flexible as the former pattern because we need to put all 'Encap's into a very specific mold.

So my question is:

Is either one of these an anti-pattern and should avoided or drawbacks simply lack of discipline and nothing to do with the pattern followed.

Algorithm for pattern recognition of sticks patterns

I'm trying to come out with an algorithm to detect a simple 1D pattern constituted by 1D sticks, where each stick is characterized by an intensity, so that such pattern can be detected in another signal comprised by many sticks. In order to detect such pattern in the target signal the requirements would be that the intensities should match (with some tolerance) the "model" stick pattern and the distances between the sticks in the "model" should also be matched (again with some tolerance).

This is a picture depicting the problem I'd like to resolve:

enter image description here

I have tried different approaches that include going through all the sticks in the target spectrum but in all cases the computational time increases exponentially with the number of sticks

Multiple values method response patterns

I am writing service objects that do many things. A service object can look like this:

class SignUpService
  def initialize(params)
    @params = params
  end

  def call
    begin
      org = create_organization!(@params[:org_params])
      log(:org_created, org)

      team = create_team!(org)
      log(:team_created, team)

      account = create_account(team)
      log(:account_created, account)

      send_email(:welcome, account)

    rescue => e
      send_email(:error_alert, @params)
      log(:report_error, e)
    end

  end
end

The SignUpService has many collaborators and has many side effects. Since this class is typically called in a controller its return value can determine if a page re-render or redirect can happen. I'm never really comfortable sending simple objects or truthy values back. I'm wondering if there's a pattern similar to returning a tuple in elixir that I can read about. I'm interested in a pattern that will let the caller know how to proceed depending on various types of responses and the data that yielded it.

Is encapsulation an overkill for non-library code and/or open source?

Encapsulation can be very useful when you are developing a library/api that will be used by 3rd parties, as you only want to expose that which is needed.

But when you have an open source library, or an internal code base develop by a product team, what is the value of encapsulation?

I can only think it's useful for 2 reasons:

1) Preventing a junior developer from misusing internal methods/variables from a class? Although this could be achieved by good documentation/comments/training on how to use the code.

2) Providing intent and implicit documentation. By having only a handful of public methods, it's easy for new comers to understand what is the interface of that class, and potentially means they don't need to understand all the implementation details. If all the methods were public it'd be hard to understand the interface.

Other than these 2, what are other benefits when it comes to open source code or internal code bases?

How to synchronize a statefull session bean object with the view communicating only delta values?

We have a big session object held in the web server using Spring session scope (says an object that represents a business object). Due to the expensive size of this bean, we manage to communicate with the view only delta attributes. For now, we know that Java reflection allows applying partial updates on the bean structure by processing fields information. We can manage this by computing the information sent by the view and calculating the differences with the server objects.

To ilustrate the problem more precisely, suppose the following JSON as the session-bean (Java classes) holds in session by Spring:

// session-bean
{
  "person": {
    "name": "Foo",
    "age": 18,
    "father": {
      "name": "Bar"
    },
    "phones": [{
      "number": 123456789
    }, {
      "number": 987654321
    }]
  }
}

Besides that, suppose that we use the following session-view structure (also holds on the session) to store information about the information presented at the view.

// session-view
[{
  "path": "person.name",
  "value": "Foo"
}, {
  "path": "person.age",
  "value": 18
}, {
  "path": "person.father.name",
  "value": "Bar"
}, {
  "path": "person.phones[0].number",
  "value": 123456789
}, {
  "path": "person.phones[1].number",
  "value": 987654321
}]

In this context, when the user sends a view-request with updates, says:

// view-request
{
  "updates": [{
    "path": "person.age",
    "path": 20
  }]
}

We use the path of each update object from view-request to find the equivalent field on the session-bean and update it (In this example "person.age"). Besides that, during the user view-request processing, if the server changes a property from the session-bean, ex:

public class PersonService {
  @Autowired
  public Person person;

  public void updateFather() {
    person.getFather().setName("Baz");
  }
}

We recompute the session-view to update each object with new information and return only delta information to view. In this example after PersonService finished their processing, the view-response will be:

// view-response
[{
    "path": "person.age",
    "path": 20
  }, {
    "path": "person.father.name",
    "value": "Baz"
}]

And the session-view will be updated to the following:

// session-view
[{
  "path": "person.name",
  "value": "Foo"
}, {
  "path": "person.age",
  "value": 20 // <- changed
}, {
  "path": "person.father.name",
  "value": "Baz" // <- changed
}, {
  "path": "person.phones[0].number",
  "value": 123456789
}, {
  "path": "person.phones[1].number",
  "value": 987654321
}]

This example illustrate the case of values modification, but besides that, we have to synchronized when objects are deleted, created or re-arranged in references and lists.

Therefore, the question is: besides this approach, exists some design-pattern or Spring/Java library that is more indicated to execute this processing?

What is the difference between Factory method design pattern and Bridge pattern?

Hello All,

Could someone please explain me the difference between Factory method design pattern and Bridge pattern?

Because from my understanding, both these design patterns are using to separate interface and implementation:

Decoupling abstraction from implementation. Abstraction separates the client code from the implementation. So, the implementation can be changed without affecting the client code and the client code need not be compiled when the implementation changes.

Factory Method:

Problem without Factory method:

There are cases where we have a library with some classes to implement the client business logic. From the client application we create objects of the library classes to complete the task.

But sometimes, based on the client requirement to incorporate additional functionality, we might need to add additional classes in the library. Then we need to create objects of the new classes in the client application.

So, each time a new change is made at the library side, Client would need to make some corresponding changes at its end and recompile the code.

Using Factory Method:

To avoid this problem, we decouple object creation from client application using Factory method. Client just needs to make call to library’s factory method without worrying about the actual implementation of creation of objects.

So we create Factory method to create objects and move it to the separate implementation file. Now the implementation file is the only one that requires knowledge of the derived classes. Thus, if a change is made to any derived class, or any new class is added, the implementation file is the only file that needs to be recompiled. Everyone who uses the factory will only care about the interface, which should remain consistent throughout the life of the application.

Client Application interacts -> Factory method and calls--> Implementation

If I take the below sample program, after adding any class or any change in the class is it enough to recompile only Vehicle.cpp file? And also when creating factory method, do we use static method?

Vehicle.h

#include <iostream> 
using namespace std; 

enum VehicleType { 
    VT_TwoWheeler,    VT_ThreeWheeler,    VT_FourWheeler 
}; 

// Library classes 
class Vehicle { 
public: 
    virtual void printVehicle() = 0; 
    static Vehicle* Create(VehicleType type); 
}; 
class TwoWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am two wheeler" << endl; 
    } 
}; 
class ThreeWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am three wheeler" << endl; 
    } 
}; 
class FourWheeler : public Vehicle { 
    public: 
    void printVehicle() { 
        cout << "I am four wheeler" << endl; 
    } 
}; 

Vehicle.cpp (Implementation file)

// Factory method to create objects of different types. 
// Change is required only in this function to create a new object type 
Vehicle* Vehicle::Create(VehicleType type) { 
    if (type == VT_TwoWheeler) 
        return new TwoWheeler(); 
    else if (type == VT_ThreeWheeler) 
        return new ThreeWheeler(); 
    else if (type == VT_FourWheeler) 
        return new FourWheeler(); 
    else return NULL; 
} 

Client.h file

// Client class 
class Client { 
public: 

    // Client doesn't explicitly create objects 
    // but passes type to factory method "Create()" 
    Client() 
    { 
        VehicleType type = VT_ThreeWheeler; 
        pVehicle = Vehicle::Create(type); 
    } 
    ~Client() { 
        if (pVehicle) { 
            delete[] pVehicle; 
            pVehicle = NULL; 
        } 
    } 
    Vehicle* getVehicle()  { 
        return pVehicle; 
    } 

private: 
    Vehicle *pVehicle; 
}; 

// Driver program 

int main() { 
    Client *pClient = new Client(); 
    Vehicle * pVehicle = pClient->getVehicle(); 
    pVehicle->printVehicle(); 
    return 0; 
}

Please provide your thoughts on this.

Thanks in advance.

Design pattern for inheriting across modules

I have a BaseClass object with two ChildClass objects inheriting from it. Each of these is a significant bit of code (>1000 lines) and they each have their own module. So the structure is as follows:

Module 1 with BaseClass

from abc import ABCMeta

class BaseClass(metaclass=ABCMeta):

Module 2 with ChildClass 1

from module1 import BaseClass

class ChildClass1(BaseClass):

Module 3 with ChildClass 2

from module1 import BaseClass

class ChildClass2(BaseClass):

At the moment I am using (I think) a Factory Design Pattern, where I have a function in a separate module controlling which ChildClass is called:

Module 4 with Class Controller

from module2 import ChildClass1
from module3 import ChildClass2

def controller():
    if condition:
        return ChildClass1()
    else:
        return ChildClass2()

I can't put this function in Module 1 because I will end up with circular imports so currently it is sitting in its own module.

A previous version of the code had the controller as a staticmethod to the BaseClass in Module 1 with the import ChildClass statements within the staticmethod, but I didn't like that pattern so I changed it to the current structure.

My question is - Is there a better design pattern that I can use without having to put everything in the same module?