1

I have a bunch of Actions in the dApp i'm building. Each action has different data associated with it. At the same time, they have a few common fields. Is there a way to model this to handle the different data associated with it?

Or do I have to make different structs for each action type I have?

Note that If I have 1 struct for all my action types it makes my code cleaner to write. I.e. I can keep the loop and common testing conditions DRY.

If I have multiple structs I have to loop through each different struct so that adds one loop per struct (plus other code that tests common members). Given this concern, is there a suggested way to handle structs with different data?

enum ActionType { A, B, C }
struct Action {
    ActionType actionType;
    string name;
    string description;
    uint createdAt;
    // should i put optional data fields?
    string someFieldOnlyExistsForA;
    bool someBoolOnlyExistsForB;
    uint someIntOnlyExistsForC;
}

//example what i mean

Action[] actions;

for (uint i = 0; i < actions.length; i++) {
    if (actions[i].createdAt < now - 1000) {
        if (actions[i].actionType == A) {do something with the string field}
        if (actions[i].actionType == B) {do something with the bool field}
        if (actions[i].actionType == C) {do something with the int field}
    }
}

vs

for (uint i = 0; i < A_actions.length; i++) {
    if (Aactions[i].createdAt < now - 1000) {
    }
}
for (uint i = 0; i < B_actions.length; i++) {
    if (Bactions[i].createdAt < now - 1000) {
    }
}
for (uint i = 0; i < C_actions.length; i++) {
    if (C_actions[i].createdAt < now - 1000) {
    }
}
2
  • I do not understand, you are showing the solution. what is your problem?
    – Jaime
    Commented Jun 10, 2018 at 7:18
  • I don't understand which is the 'accepted'/'recommended' way to do things and why. I couldn't find anything on struct inheritance and doing it like option 1 implicitly has more fields saved into storage that are not necessary. Meanwhile option 2 is less DRY. Was wondering if there is a recommended way of handling this type of situation Commented Jun 10, 2018 at 20:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.