mercredi 7 juin 2023

Resolve code duplication using Generics VS Inheritance

I have a common reader for three different classes, but there is some code duplication because the reader has different methods for each of the classes A, B, and C. Is there anyway I can make the code cleaner? e.g., by having only one read method?

Any insights would be appreciated :)

(Due to legacy issues I wasn't able to let A, B, and C extend another superclass or implement another superclass.)

public class ReaderForABC {

    public A readA() {
        doLotsOfCommonThings();
        A result = computeA();
        return result;
    }
    public B readB() {
        doLotsOfCommonThings();
        B result = computeB();
        return result;
    }
    public C readC() {
        doLotsOfCommonThings();
        C result = computeC();
        return result;
    }
    
    private static void doLotsOfCommonThings(){}
    private static A computeA(){
        //do something common
        //call helper function to compute A
        /*This helper function is similar to computeA(), 
        where there are some code duplication and some differences in the end
        (and also a cascade of calls to similar functions like computeA())
        */
         
    }
    private static B computeB(){
        //do something common
        //call helper function to compute B
        /*This helper function is similar to computeB(), 
        where there are some code duplication and some differences in the end
        (and also a cascade of calls to similar functions like computeB())
        */
    }
    private static C computeC(){
        //do something common
        ///call helper function to compute B
        /*This helper function is similar to computeC(), 
        where there are some code duplication and some differences in the end
        (and also a cascade of calls to similar functions like computeC())
        */
    }
}

To use the reader:

ReaderForABC readerForABC = new ReaderForABC()
A a = readerForABC.readA();
A b = readerForABC.readB();
//...similarly for C.

The main issue I face is that those readX and computeX functions have lots of code duplication because computeX calls a cascade of other functions that have code duplication for each type of A, B, and C. If I have a way to address code duplication in readX, I can address similarly in computeX and other functions that are called within it.

I tried to use generics, but it made things worse...because it has to decide on which action to take by checking class type

public <T> T read(Class<T> classType) {
        doLotsOfCommonThings();
        T result;
        if (classType.getSimpleName().equals("A")) {
            result = (T) computeA();
            return result;
        } else if (classType.getSimpleName().equals("B")) {
            result = (T) computeB();
            return result;
        }
        //...handle C similarly
    }

(edited computeX() to make things more clear, hopefully)

Javascript Design Patterns Streaming Service Project

Design for a Music Streaming Service Project

Use the Strategy pattern to handle various music formats, such as Mp3 and Wav.
Implement the Observer pattern to monitor the music playback status.
Define a Subject interface to update the Ui whenever there are any changes. Apply the Factory pattern to create objects required for music playback. For example, when playing Mp3 format music, create an Mp3 Decoder object, and for Wav format music, create a WavDecoder object.
Utilize the Composite pattern to structure music playlists. Use the Facade pattern to determine whether the user is a member or not.

I'm not sure if this design I came up with is accurate. I'm a beginner and currently studying, but I don't know the proper usage of design patterns or the correct order to apply them. Could you show me a simple UML diagram or help me improve the part I designed? Also, please guide me on the appropriate sequence for using design patterns.

If the design I came up with is strange, you can provide a new design as well. Please leave multiple feedback.


I felt like I used multiple patterns, but I had the sense of designing in order to use design patterns, and I'm not sure about the design for the music streaming service.

How to reference the correct class in a parallel class hierarchy

I have a base class that produces a text depending on its internal state. This is achieved by a state machine.

public abstract class BaseState
{
    // State functions

    public abstract string GetText();

    public abstract bool ShouldUpdateText();
}


public class ObjectBase // Context class
{
    public BaseState State;

    public string Text;

    public float Data1;

    public void UpdateText()
    {
        if(State.ShouldUpdateText())
       {
            Text = State.GetText();
       }
    }

    // State machine functions
}

State objects need a reference to the context class for its logic.

Derivations of the base context class have their own state object classes which need to work on that class.

So the class hierarchy of base context class is paralleled by the state class hierarchy.

public class DerivedObject1 : ObjectBase 
{
   public int[] Data2;
}

public class DerivedObject2 : DerivedObject1 
{
   public bool Data3;
}


/* Needs to work with an ObjectBase */
public class State1 : BaseState
{
   public override bool ShouldUpdateText()
   {
        return Data1 > 0;
   }
}

/* Needs to work with a DerivedObject1 */
public class State2 : BaseState
{
   public override bool ShouldUpdateText()
   {
        return Data2.Length > 2;
   }
}

/* Needs to work with a DerivedObject2 */
public class State3 : State2 
{
   public override bool ShouldUpdateText()
   {
        return base.ShouldUpdateText() && Data3;
   }
}

I'm trying to figure out what is the best way to provide a context reference to state classes as they all have different types although they share their highest parent.

Some options I considered

Type-casting through base class reference -- Feels like a code smell

class BaseState
{
    public ObjectBase Context;
}

public class State2 : BaseState
{
   public override bool ShouldUpdateText()
   {
        return (Context as DerivedObject1).Data2.Length > 2;
   }
}

Intermediate parent states for correct typed references

Doesn't work when there are states deriving from states, such as State2 & State3 in the initial example.

class StateForDerivedObject1 : BaseState
{
    public DerivedObject1 Context;
}

public class State2 : StateForDerivedObject1 
{
   public override bool ShouldUpdateText()
   {
        return Context.Data2.Length > 2;
   }
}

What is the best way to handle this problem?

Is there a better way to design the architecture that avoids this problem altogether?

Thanks

Dynamically changing schema of DB at runtime

We are onboarding Distributed tracing in our service. For that we want to add traceId column in Dynamo DBs for which streams are enabled. Other DBs which do not have DDB streams enabled should remain same as before. In future we might also get a usecase wherein we need to switch on the DDB streams in an existing DDB and that would require adding traceId in that DB as well.

I wanted suggestions on a design that would ease switching between DDB schema with trace and without trace dynamically at runtime without requiring us to add/remove obj.setTrace(someTrace) statements every time we switch

I tried the design but the problem is that DBOperations expects a generic class (Eg: method void save(T object)) and we cannot setTraceId() in a generic class

Is there a design pattern for logic performed on multiple event listeners

I have logic that is performed on steps on multiple different events. for example some logic is done on mousedown which changes some shared state that mousemove uses which also changes some shared state that finally mouseup uses. for example it might look something like this

function handleMouseDown(){
...
setState1()
...
setState2()
}
function handleMouseMove(){
...
consumeState2
...
consumeState1
setState3()
...
}

function handleMouseUp(){
...
consumeState3
...
}

The problem is that I feel that dependancy between the logic performed in those 3 events is implicit, which is in my opinion makes it hard to figure out what the code does especially if you considered that I have more than one task performed the same way. So my question is there a design pattern for this?

mardi 6 juin 2023

I want to create html design something like this can anyone help me please

reference image

I want to create html design like this image reference image.i just want to first arrow design so that i will do it my self remaining .please help me if anyone have any idea about it please use any icon but i want to same design frame.

Python - update the same list and dict using the output of different functions, no code repetition

I have a list and a dict, whose values I'm updating in different parts of the code using a structure like this:

final_list = []
final_dict = {}

for iter_1 in iterables_1:

    if condition_1:
        ret_1, ret_2 = function(...)
        if ret_1 is not None and ret_2 is not None:
            final_list.append(ret_1)
            final_dict[iter] = ret_2
    
    elif condition_2:
        for iter_2 in iterables_1:
            for iter_3 in iterables_3:
                ret_1, ret_2 = function(...)
                if ret_1 is not None and ret_2 is not None:
                    final_list.append(ret_1)
                    final_dict[iter] = ret_2

Now, everything works, but the lines:

ret_1, ret_2 = function(...)
if ret_1 is not None and ret_2 is not None:
    final_list.append(ret_1)
    final_dict[iter] = ret_2

are repeated (this is an oversimplification, the real code is much longer and this situation occurs more often).
In a case like this, how can I avoid this repetition?

EDIT: I forgot to mention it, one option would be to move the repeated lines to function. However, unless I'm missing something, this would require having final_list and final_dict as both arguments and return value of said function, so something like:

def function(final_list, final_dict, ...):
# calculate ret_1, ret_2
if ret_1 is not None and ret_2 is not None:
    final_list.append(ret_1)
    final_dict[iter] = ret_2

return final_list, final_dict

final_list = []
final_dict = {}

for iter_1 in iterables_1:

    if condition_1:
        final_list, final_dict = function(final_list, final_dict, ...)
    elif condition_2:
        for iter_2 in iterables_1:
            for iter_3 in iterables_3:
                final_list, final_dict = function(final_list, final_dict, ...)

But I'm not sure this is good practice either.