jeudi 22 avril 2021

How can I represent an infinite loop in a sequence diagram?

Can I say the number of iterations is (1..*)? or put a condition as [true]? How do I do this? This is to let a user attempt to login an infinite number of times.

Can someone explain what is this HeapQueue data structure and why designed it

https://learn.unity.com/project/2d-platformer-template

Have been struggling on studying this unity tutorial project. Generally speaking I am confused about the method names that are used here.

Also, I researched the algorithm of sift up and sift down but the code here seems opposed to the normal heap concept. Although there are annotation I can't fully understand this pop method.

    public class HeapQueue<T> where T : IComparable<T> {
    List<T> items;

    public int Count { get { return items.Count; } }

    public bool IsEmpty { get { return items.Count == 0; } }

    public T First { get { return items[0]; } }

    public void Clear() => items.Clear();

    public bool Contains(T item) => items.Contains(item);

    public void Remove(T item) => items.Remove(item);

    public T Peek() => items[0];

    public HeapQueue()
    {
        items = new List<T>();
    }

    public void Push(T item)
    {
        //add item to end of tree to extend the list
        items.Add(item);
        //find correct position for new item.
        SiftDown(0, items.Count - 1);
    }

    public T Pop()
    {

        //if there are more than 1 items, returned item will be first in tree.
        //then, add last item to front of tree, shrink the list
        //and find correct index in tree for first item.
        T item;
        var last = items[items.Count - 1];
        items.RemoveAt(items.Count - 1);
        if (items.Count > 0)
        {
            item = items[0];
            items[0] = last;
            SiftUp();
        }
        else
        {
            item = last;
        }
        return item;
    }


    int Compare(T A, T B) => A.CompareTo(B);

    void SiftDown(int startpos, int pos)
    {
        //preserve the newly added item.
        var newitem = items[pos];
        while (pos > startpos)
        {
            //find parent index in binary tree
            var parentpos = (pos - 1) >> 1;
            var parent = items[parentpos];
            //if new item precedes or equal to parent, pos is new item position.
            if (Compare(parent, newitem) <= 0)
                break;
            //else move parent into pos, then repeat for grand parent.
            items[pos] = parent;
            pos = parentpos;
        }
        items[pos] = newitem;
    }

    void SiftUp()
    {
        var endpos = items.Count;
        var startpos = 0;
        //preserve the inserted item
        var newitem = items[0];
        var childpos = 1;
        var pos = 0;
        //find child position to insert into binary tree
        while (childpos < endpos)
        {
            //get right branch
            var rightpos = childpos + 1;
            //if right branch should precede left branch, move right branch up the tree
            if (rightpos < endpos && Compare(items[rightpos], items[childpos]) <= 0)
                childpos = rightpos;
            //move child up the tree
            items[pos] = items[childpos];
            pos = childpos;
            //move down the tree and repeat.
            childpos = 2 * pos + 1;
        }
        //the child position for the new item.
        items[pos] = newitem;
        SiftDown(startpos, pos);
    }
}

}

This is how the pop method is used on the tick method in another class

enter image description here

How to represent polymorphic pattern when designing mongo db schema using a collection-relationship diagram

I'm designing a schema for mongo db to support app data modeling using a collection-relationship diagram that is widely used in official mongo db modeling documentation and tutorials. In some collections, I decided the best approach is to use Polymorphic Pattern.

As a simple fictional example, consider I want to embed profile information into a users collection. From the business domain, I know it exists two types of profiles: reader and administrator. Each profile shares some data fields, but also has different fields.

Applying the polymorphic pattern, a reader profile could be represented in a document like:

{
 _id: "<ObjectId>",
 email: "reader@email.com",
 ...
 profile: {
   type: "reader",
   name: "Reader's Name",
   total_reads: 1000,
   ...
 }
}

And an administrator profile could be represented in a document like:

{
 _id: "<ObjectId>",
 email: "administrator@email.com",
 ...
 profile: {
   type: "administrator",
   name: "Administrator's Name",
   total_edits: 100,
   ...
 }
}

As you can see, it implies in two differents profile subdocuments structure depended on type field.

How I represent this polymorphic pattern when designing a schema using a collection-relationship diagram?

Do you create a service to share a single function between components?

When I have a single function that isn't part of a collection of functions that serve the same purpose I don't bother creating a Service for it.

I just have a separate helper.ts file that holds those functions.

I was just wondering how others solve that problem

Creating a tree with specific depth and children

I am trying to generate a random tree using the composite pattern design. The tree must have a specified depth, and each node in the tree must have a specified number of children. In the node class, I have a List<> structure, which holds all the children of that particular node. I have attached the composite class with just the relevant code: (Note, componentNode is the interface of the composite pattern, a componentNode can be either a compositeNode or a leafNode, which is why the List<> holds componentNode).

class compositeNode implements componentNode
{
    //a compositeNode holds a list of other components inside of it 
    List<componentNode> components = new ArrayList<componentNode>();

    String name;

    public compositeNode(String inName)
    {
        name = inName;
    }

    public List<componentNode> getList()
    {
        return components;
    }

    public void addComponent(componentNode newComponent)
    {
        components.add(newComponent);
    }

    public String getName()
    {
        return name;
    }

}

This is my attempt at generating the tree:

    public static void treeGeneration()
    {
        int numChildNodes = 2;
        int treeDepth = 2;
        //getRandomNumber(1,5); 
        compositeNode tree = new compositeNode("Root");
        compositeNode currNode = tree;
        compositeNode currDepth;        

        for (int x=0; x<numChildNodes; x++)
        {
            compositeNode node = new compositeNode(generateName());
            tree.addComponent(node);
        }

        List<componentNode> treeList = tree.getList();
        Iterator<componentNode> iterTree = treeList.iterator();

        
        while(iterTree.hasNext())
        {
            currNode = (compositeNode) iterTree.next();//iterate through the children of the root node
            for (int i=1; i<treeDepth; i++)//accessing the child nodes so depth is 1
            {
                for (int x=0; x<numChildNodes; x++)
                {       
                    compositeNode newNode = new compositeNode(generateName());
                    currNode.addComponent(newNode);//add newly created nodes to the 
                }
                List<componentNode> currList = currNode.getList();
                Iterator<componentNode> iterList = currList.iterator();//iterate through the newly created nodes to add nodes to them 
                currNode = (compositeNode) iterList.next();
            } 
        }

The issue in my code is that the specified depth is only reached for the FIRST node of each list. For example, this is what the tree looks like when I execute it with a depth of 3, with each node having 2 children:

                         Root
                      /       \ 
                  Node1         Node2 
                 /     \        /     \
              Node3   Node4   Node7   Node8
             /    \          /     \
          Node5  Node6      Node9  Node10

As you can see node4 and node8 do not have any children, when I need them to have children. I understand the issue in my code is because once I have reached the end of the for loop where I am iterating until I reach the depth, it moves onto the next node. However, I have no clue as to how I am supposed to fix it. I have been stuck on this problem for hours now, any help will be appreciated. Thanks :)

Avoid if and switch statement and more generic approach

I want to avoid the use of "if" and "switch" statements which deal with specific cases and instead taking a more generic approach.

Requirement: Based on a number of requirements which are detailed below, the status of an Order may be determined to be "Confirmed", "Closed" or "AuthorisationRequired".

Inputs:

IsRushOrder: bool
OrderType: Enum (Repair, Hire)
IsNewCustomer: bool
IsLargeOrder: bool

Outputs:

OrderStatus: Enum (Confirmed, Closed, AuthorisationRequired)

Requirements (Applied in priority order from top to bottom):

-Large repair orders for new customers should be closed
-Large rush hire orders should always be closed
-Large repair orders always require authorisation
-All rush orders for new customers always require authorisation
-All other orders should be confirmed

==========================================================================================

One way i could think of implementing withoud using IF is by populating OrderStatus in collection and querying using LINQ This implementaion will get complicated quickly as we add more statuses.

public class OrderStatusAnalyzer
{
    protected static List<OrderStatus> OrderStatuses;

    public OrderStatusAnalyzer()
    {
        OrderStatuses = OrderStatusCollection.Get();
    }

    public string GetOrderStatusTypeByOrderInput(OrderInput orderInput)
    {
        var orderStatusTypes = from orderStatus in OrderStatuses
                               where orderStatus.IsNewCustomer == orderInput.IsNewCustomer
                                     && orderStatus.IsLargeOrder == orderInput.IsLargeOrder
                                     && orderStatus.IsRushOrder == orderInput.IsRushOrder
                                     && orderStatus.OrderType == orderInput.OrderType
                               orderby orderStatus.Priority ascending
                               select orderStatus.OrderStatusType;

        var statusTypesList = orderStatusTypes.ToList();
        var orderStatusType = !statusTypesList.Any() ? "VehicleRepairOrder.Order.AllOtherOrders" : statusTypesList[0];

        return orderStatusType;
    }
}
public static class OrderStatusCollection
{
    public static List<OrderStatus> Get()
    {
        // Note:
        // 1) If we have to avoid referencing null, then we can populate the data with probabilities. Populating data with probabilities will become hard Maintain as we add more status   
        // 2) this is also violating O(Open for extension and closed for modification) of SOLID principle 
        // 3) instead of passing null, if you pass actual unit test will fail
        var orderStatuses = new List<OrderStatus>
        {
            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = true, OrderType = OrderTypeEnum.Repair,
                IsRushOrder = null,
                Priority = 1, OrderStatusType = "VehicleRepairOrder.Order.LargeRepairNewCustomerOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = null, OrderType = OrderTypeEnum.Hire, IsRushOrder = true,
                Priority = 2, OrderStatusType = "VehicleRepairOrder.Order.LargeRushHireOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = null, OrderType = OrderTypeEnum.Repair,
                IsRushOrder = null,
                Priority = 3, OrderStatusType = "VehicleRepairOrder.Order.LargeRepairOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = null, IsNewCustomer = true, OrderType = OrderTypeEnum.Any, IsRushOrder = true,
                Priority = 4, OrderStatusType = "VehicleRepairOrder.Order.AllRushNewCustomerOrder"
            },

        };

        return orderStatuses;
    }
}

React - Component that strictly depends on context

Have you ever been in a use case where a component strictly depends on a context?

Imagine this situation:

  1. Make a fetch to the same amount to data.

  2. Save the data in a map, in a context

  3. Only after the context state update has finished, render all the data in a FlatList

    3.1 Then pass an id to the component.

      <MyComponent id={id} /> 
    

    3.2 The component, which is a consumer of the context, does:

     const {isLiked} = myContext.getItem(id); // Get a most fresh prop from the context
    

    3.3 The component renders everything using the context data

Not sure if this is a good design, but saving data in a context after fetches is a requirement for my use case.

As you can see, now my component strictly depends on a Context, because if data is not in the context, then it will simply fail.

Should I be more flexible? and pass "falsy" props to it (just to prevent the situation of using this component without storing data in context)?

<Card id={id} isLiked={isLiked} />

Is it a bad design no have components strictly depending on Context API?