mercredi 19 février 2020

Do split one class hierarchy into several or not?

For now we have a .NET application which leans on the standard .NET XML serialization/deserialization mechanism. The example is simplified but the meaning is the same.

public abstract class Shape
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("level")]
    public int Level { get; set; }

    public abstract void Draw();
    public abstract void Clear();
    public abstract void Scale(double scale);
}

[XmlType("Circle")]
public class Circle : Shape
{
    public double Radius { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

[XmlType("Rectangle")]
public class Rectangle: Shape
{
    public double Height { get; set; }
    public double Width { get; set; }

    public override void Draw() {}

    public override void Clear() {}

    public override void Scale(double scale) {}
}

public class Picture
{
    public double Scale { get; set; }
    [XmlArrayAttribute("Shapes")]
    public Collection<Shape> Shapes { get; set; }

    public void Setup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Draw();
        }

        foreach (Shape shape in Shapes)
        {
            shape.Scale(Scale);
        }
    }

    public void Cleanup()
    {
        foreach (Shape shape in Shapes)
        {
            shape.Clear();
        }
    }

    public static Picture FromXml(XmlReader xmlReader)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Picture));
        return serializer.Deserialize(xmlReader) as Picture;
    }
}

And for example the input XML file will look like:

<Picture>
    <Scale>0.9</Scale>
    <Shapes>
        <Circle id="1">
            <Radius>1.5</Radius>
        </Circle>
        <Circle id="2">
            <Radius>3</Radius>
        </Circle>
        <Rectangle id="3">
            <Height>300</Height>
            <Width>300</Width>
        </Rectangle>
    </Shapes>
</Picture>

But model classes contain a logic and seems that it breaks a single responsibility principle. And therefore we don't know does it make sense to split that logic into several classes or not?

If yes, then how? Because once we read the XML file, all objects are accessible only as Shape objects and therefore we will have to explicitly cast the object either before passing if to the handler class or inside that method, for example:

public abstract class Drawer
{
    public abstract void Draw(Shape shape);
}

public class CircleDrawer : Drawer
{
    public override void Draw(Shape shape){
    {
        Circle circle = shape as Circle;
        if (circle == null)
        {
            throw new ArgumentException("Passed object is not of type Circle");
        }
    }
}

If that issue is known, please just redirect me to that resource.

Thank you in advance.

Should notifications be removed using removeObserver(self) in iOS?

Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self.

Is there any guideline from Apple about best practice of removing notification observers?

Kubernetes design pattern for an existing application which spawns a new process for every single client session?

I'm currently working on a legacy application which uses a ServiceFactory process to spawn new processes which handle current and all subsequent requests from a client. This one process per client session is designed to retain large volume of data queried and analyzed in-memory to serve the follow-up requests from the same client. Once the client terminates the connection, the process exits.

What would be an equivalent implementation using Kubernetes?

mardi 18 février 2020

Modelling actions in Java

I am looking to standardize common actions using a design pattern but I am not sure which one is the best.

Let's say if we start off with two service Java classes with two operations/methods each.

class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

class Service2 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

Two services are sharing the same algorithms so naturally, I would want to refactor performSomething() and performSomethingElse(). My approach is to create two single-method classes for each refactored method.

interface Action {
    public void run();
}
class PerformSomething implements Action {
    public void run() {}
}
class PerformSomethingElse implements Action {
    public void run() {}
}

class Service1 {
    private PerformSomething algo1;
    private PerformSomethingElse algo2;

    public void businessUseCase1() {
        algo1.run();
        algo2.run();
    }

}

I feel like this simple approach is naive and I am very sure there's a more suitable design pattern that can represent an Action instead of creating a custom interface to present Actions.

Design pattern or approach recommended for working with 2 external API clients

Due to the lack of functionality on API A our team is planning to move to API B in about 6 months, due to contract we are required to continue operations using the first api, but we also need to start implementing the second option, as you can imagine the code right now is coupled to the first API and since API B has the same functionality as API A plus some additional that need to be implemente. Taking into account that the provider could change to API C (decided by the manager maybe) what is the best approach to tackle this issue.

We we trying to start by using Factory design pattern to handle multiple api clients that support the same functionality. but how does the system picks use api a, b, or c?

Any help or tip is appreciated, we are using python 3+.

C# Design pattern for periodic execution of multiple Threads

I have a below requirement in my C# Windows Service.

  1. At the starting of Service, it fetches a collection of data from db and keeps it in memory.
  2. Have a business logic to be executed periodically from 3 different threads.
  3. Each thread will execute same bussiness logic with different subset of data from the data collection mentioned in step 1. Each thread will produce different result sets.
  4. All 3 threads will run periodically if any change happened to the data collection.

When any client makes call to the service, service should be able to return the status of the thread execution.

I know C# has different mechanisms to implement periodic thread execution. Timers, Threads with Sleep, Event eventwaithandle ect., I am trying to understand Which threading mechanism or design pattern will be best fit for this requirement?

Implementing Factory Method instantiation on AWS Lambda

I am building a serverless data extractor on AWS lambda. The current design involves several subclasses of data extractors functioning on different modes (full extraction and incremental for example) which need to be instantiated using a factory class based on a configuration passed into the Lambda function. However the question remains, how suitable it is to have all of this wrapped into a single deployement bundle on a single lambda function.

While I have also considered using state machines to achieve this, I would appreciate if someone could give me a heads up on why or why not the earlier method would not be suitable for the serverless architecture.