php – too many if statements when handling forms and scattered classes?

i have a website that has multiple forms, after the user submits one of those forms, it goes to a handler page that has all the handling stuff for all forms,either it enters the form data to the database, or sends it to a class that gets elements from the database and displays it dynamically, and more stuff, the thing is that the handler page has too many if statements that decide what form is submitted and what to do with it, and there are a lot of classes that does a lot of stuff, i know code with a lot of if statements is not good, how can i order the logic of my website, is there a design pattern i can use? is my way okay? i’m gonna show you an example of the logic without the actual code so you can understand better.

the handler page

if(isset($_POST('Registration')))
  {
  //send to database
  }

if(isset($_POST('login')))
  {
  //header to a page
  }

if(isset($_POST('show-menu')))
  {
  //send to a class that displays data from database dynamically
  }

if(isset($_POST('enter-dish')))
  {
  $obj = new DishValidation(// constructer parameters );
  $obj->validateDish();
  
  if (validateDish()==true){
     //send to database
     }

  }

and way other stuff


what’s also bothering me is that some if statements send to the database directly from the handler, some if statements use class to validate something, or do something else, i feel like everything on the website should be either in a class, why is the sending data to the database is directly from the handler page and other stuff are using the classes.

what can i do to fix this? i need a cleaner code with better logic and handeling.

java – Concept/Design question: Alternatives to switch/conditional statements and Enums

I am practicing design patterns and OO concepts such as inheritance in java and I’m writing an application that represents a vending machine.

I have two questions focused on ideal structure and design patterns:

  1. What is an alternative way to decide which treat from the vending machine to manufacture based on the passed name parameter of the treat object(see below there are three treat type classes derived from a treat superclass). I am currently using switch statements and conditional statements based on treat name.
  2. What is the best way to represent a list of potential variables for “brand name” of the treat. The brand names can be used by a salty treat or a sweet treat, but not by the healthy treat.

So I have a vending machine class that has a “treat” class that represents a superclass for all treats held within the machine.

The treat class has three types of objects that inherit from treat: “salty”, “sweet”, “healthy.”

Each of these types of objects will then have specific methods (like getIngredients()) and member variables (name, price) that are unique to those objects.

But I’d like to have a class that is merely a list of the brand names that can be a member variable of the salty and sweet treat objects. Healthy is different because it won’t have a brand — it will just be fruit.

For example, the Nabisco brand could be a member variable of two of the three treat types: “Oreos” (sweet), “Wheat thins” (salty).

Should I maybe use a command pattern to determine which treat to generate based on the name? I’d just like to avoid switch/conditionals if possible and use the best design patterns for each task. I’ve watched videos and have been reading tutorials on how to use patterns but I’m still unsure in these two cases which is best to use. I also can’t find a good example on stack exchange that deals with my issue there.

Should I try to use a strategy pattern to store this list of brands that has no other function but is simply an attribute stored within an object? Something like BrandStrategy –> assignBrand() –should brand even be stored in it’s own class? It seems like it should since two subclasses would use it.

Diagram of Program:

                                 VendingMachine
                                        |
                                 FactoryMethod (Creates treat based on treat "name")
                                        |
                                      Treat    (Abstract class)
                                   /    |    

                              Sweet   Salty   Healthy (Concrete classes: inherit from treat)
                                ^       ^
                                |       |       
                               Brand class (member variable of sweet & salty)

I have been reading about design patterns and best practices and I’ve been trying to avoid switch statements and conditional statements to generate specific objects and I’ve been reading that poor use of enums can create brittle code. I originally had “brand” stored as an enum but I’m realizing now that is a bad way to do it since that value is likely to change (basing this statement off of this post I researched).

Here are some of the stack exchange posts and tutorials I have read:

  1. https://stackoverflow.com/questions/61024826/what-is-the-best-way-to-structure-a-group-of-variables-that-have-a-group-of-vari
  2. Refactoring Switch Statements and is there any real use for Switch Statements at all?
  3. https://www.planetgeek.ch/2009/07/01/enums-are-evil/
  4. https://stackoverflow.com/questions/4417070/switch-statements-are-bad
  5. https://www.javatpoint.com/design-patterns-in-java
  6. https://stackoverflow.com/questions/38855909/alternative-to-enum-in-design-pattern

javascript – JS – Same recurring statements in if-else

I have this watcher in my app.vue that makes sure the right theme attribute is set on the html tag. I have a nested if/else loop, and as you can see in the code below I have two different conditions but two times the same statements.

Is there some way to code this is a more reusable way? I can imagine in some cases there are going to be more conditions with maybe the same statements.

  created() {
    const media = window.matchMedia("(prefers-color-scheme: dark)");

    this.$store.watch(
      (state) => {
        return state.settings.colorSettings.automatic;
      },
      (currentAutomaticValue) => {
        if (currentAutomaticValue) {
          media.addEventListener("change", this.setTheme);

          window.matchMedia &&
          window.matchMedia("(prefers-color-scheme: dark)").matches
            ? setThemeAttribute(themes.dark) // 1
            : setThemeAttribute(themes.default); // 2
        } else {
          media.removeEventListener("change", this.setTheme);

          this.colorSettings.darkMode
            ? setThemeAttribute(themes.dark) // 1
            : setThemeAttribute(themes.default); // 2
        }
      },
      { immediate: true }
    );
  },

Using nested if/else statements in Anydice

The problem with your nested if/else blocks is that you’re failing to close the an if block before each else. If we look at a smaller example:

if I < 19 {
    if J < 19 {
        ...
    }
    else {
        ...
    }
else {
    ...
}

we can see that the first if statement isn’t closed before the else. You can fix this by introducing a } before each else. In the small example, this would be:

if I < 19 {
    if J < 19 {
        output 12d8 + 40d8
    }
    else {
        output 12d8 + 36d8
    }
}
else {
    output 12d8 + 32d8
}

In the full example, this is:

A: 1d20
B: 1d20
C: 1d20
D: 1d20
E: 1d20
F: 1d20
G: 1d20
H: 1d20
I: 1d20
J: 1d20
if A < 19 {
 if B < 19 {
  if C < 19 {
   if D < 19 {
    if E < 19 {
     if F < 19 {
      if G < 19 {
       if H < 19 {
        if I < 19 {
         if J < 19 {
          output 12d8 + 40d8
         }
         else {
          output 12d8 + 36d8
         }
        } 
        else {
         output 12d8 + 32d8
        }
       } 
       else {
        output 12d8 + 28d8
       }
      } 
      else {
       output 12d8 + 24d8
      }
     } 
     else {
      output 12d8 + 20d8
     }
    } 
    else {
     output 12d8 + 16d8
    }
   } 
   else {
    output 12d8 + 12d8
   }
  } 
  else {
   output 12d8 + 8d8
  }
 } 
 else {
  output 12d8 + 4d8
 }
} 
else {
 output 12d8
}

This new program gives a different error message but does solve your syntax problem. The new error message is:

calculation error
Boolean values can only be numbers, but you provided "d{?}".
Depending on what you want, you might need to create a function.

Guidance for this new error after the if/else syntax has been fixed can be found in How can I execute code depending on a die value in AnyDice?

replication – ALTER TABLE statements not replicating in all tested scenarios – MariaDB

Summary

Tech: mariadb 10.3

Issue: some attempts to ALTER TABLE to change engine is not replicating.

Scenarios tested:

  • command line PHP script running ALTER statements using PDO – did not replicate
  • mysql direct command line ALTER statement – did not replicate
  • DataGrip remote connection – did replicate

The above were all run using the same user, so it’s not a permissions thing.

The Long version

I am undertaking a change to our replicated databases to convert all tables from MyISAM to InnoDB. It is A LOT of tables (over 100k, across a couple hundred DBs), so scripting it is necessary. We’ve tested the change in non-replicated environments, and all seems to be good with it in general.

I went to run a test to verify that the replication would not present a problem. When running my conversion script against a replicated test database, the primary tables all updated, but the replicants did not. I then attempted to run the query manually in mysql CLI directly. Same result – primary succeeds, replicants do nothing.

Last test I ran was to connect my IDE’s SQL editor (DataGrip) to the test DB and try modifying the schema from there. This worked!

So clearly DataGrip is doing something my script and direct CLI statement are not. I researched into commits, but everything I read says ALTER TABLE statements have an implicit commit included. I can’t find anything to enable a more verbose output from DataGrip to see what it might be doing differently.

mysql – Track SELECT statements on specific tables

I’m searching for a way to keep track of any SELECT statements on a specific table in a database where logs are not enabled. I can’t find any solutions to this except to force people to use a stored procedure to select data from the table and then log entries within that SP.

Is there a better solution to this problem? I do have full rights over processlist if that helps but given that the table I want to keep track of is pretty small, there’s a good chance I may miss the queries between calls.

Simplify IF/ELSE Statements for a Javascript Array – Multilingual Site

I have written some javascript code for a multilanguage site. The code works great but I feel like I have a lot of duplicate code. I was wondering if someone can explain how I can make this simpler or minimized. I have tried to use a forEach(function (item, index) but it does not seem to be working.

This is the original code that works….

(function () {
  var lang1 = "/en/"; //default language
  var lang2 = "/fr/"; //second language
  var lang3 = "/es/"; //third language

 var languageSwitcher = document.querySelectorAll("a(href='/languages')").forEach((el) => el.parentNode.classList.add("language-switcher"));
 document.querySelector("(data-folder='/languages')").classList.add("language-switcher");
  
  document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
 document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
  var languages = document.querySelectorAll(".languages");
  
  var language1 = document.querySelectorAll(".language-switcher .languages a(href*='"+lang1+"')");
  var language2 = document.querySelectorAll(".language-switcher .languages a(href*='"+lang2+"')")
  var language3 = document.querySelectorAll(".language-switcher .languages a(href*='"+lang3+"')")

  var windowURL = window.location.href;
  var pageURL = windowURL.split("/")(4);

  if (pageURL == undefined) {
    for (var i = 0; i < language1.length; i++) {
      language1(i).onclick = function () {
        var path = lang1 + "home";
        this.href = path;
      };
    }
    for (var i = 0; i < language2.length; i++) {
      language2(i).onclick = function () {
        var path = lang2 + "home";
        this.href = path;
      };
    }
    for (var i = 0; i < language3.length; i++) {
      language3(i).onclick = function () {
        var path = lang3 + "home";
        this.href = path;
      };
    }
  } else {
    for (var i = 0; i < language1.length; i++) {
      language1(i).onclick = function () {
        var path = lang1 + pageURL;
        this.href = path;
      };
    }
    for (var i = 0; i < language2.length; i++) {
      language2(i).onclick = function () {
        var path = lang2 + pageURL;
        this.href = path;
      };
    }
    for (var i = 0; i < language3.length; i++) {
      language3(i).onclick = function () {
        var path = lang3 + pageURL;
        this.href = path;
      };
    }
  }

 document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
  document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
  document.querySelectorAll('(data-folder="/languages") .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));

  var languageLinks = document.querySelectorAll(".language");

  for (var i = 0; i < languageLinks.length; i++) {
    var navURL = languageLinks(i).href;
    if (windowURL.indexOf(lang1) != -1) {
      languages.forEach((el) => el.classList.remove("active"));
      languages(0).classList.add("active");
      if (navURL.indexOf(lang1) != -1) {
        languageLinks(i).closest("div").style.display = "block";
      } else {
        languageLinks(i).closest("div").style.display = "none";
      }
    } else if (windowURL.indexOf(lang2) != -1) {
      languages.forEach((el) => el.classList.remove("active"));
      languages(1).classList.add("active");
      if (navURL.indexOf(lang2) != -1) {
        languageLinks(i).closest("div").style.display = "block";
      } else {
        languageLinks(i).closest("div").style.display = "none";
      }
    } else if (windowURL.indexOf(lang3) != -1) {
      if (navURL.indexOf(lang3) != -1) {
        languages.forEach((el) => el.classList.remove("active"));
        languages(2).classList.add("active");
        languageLinks(i).closest("div").style.display = "block";
      } else {
        languageLinks(i).closest("div").style.display = "none";
      }
    } else {
      if (navURL.indexOf(lang1) != -1) {
        languages.forEach((el) => el.classList.remove("active"));
        languages(0).classList.add("active");
        languageLinks(i).closest("div").style.display = "block";
      } else {
        languageLinks(i).closest("div").style.display = "none";
      }
    }
  }

  var active = document.querySelector(".language-switcher .active");
  active.closest(".language-switcher").prepend(active);
  document.querySelectorAll(".header a").forEach((el) => (el.style.visibility = "visible"));
  languageSwitcher.style.display = "flex";
})();

I have attempted to use a forEach function and an array but it is not working.

 (function () {
  var lang = ("/en/", "/fr/", "/es/");
  
  document
    .querySelectorAll("a(href='/languages')")
    .forEach((el) => el.parentNode.classList.add("language-switcher"));
  document
    .querySelector("(data-folder='/languages')")
    .classList.add("language-switcher");

  document
    .querySelectorAll(".language-switcher .header-nav-folder-item")
    .forEach((el) => el.classList.add("languages"));
  document
    .querySelectorAll(
      ".language-switcher .header-menu-nav-item:not(:first-child)"
    )
    .forEach((el) => el.classList.add("languages"));

  var languages = document.querySelectorAll(".languages"); //langauge switcher language options

  document
    .querySelectorAll(".header-nav-item:not(.language-switcher) a")
    .forEach((el) => el.classList.add("language"));
  document
    .querySelectorAll(".header-menu-nav-item:not(.language-switcher) a")
    .forEach((el) => el.classList.add("language"));
  document
    .querySelectorAll('(data-folder="/languages") .header-menu-nav-item a')
    .forEach((el) => el.classList.remove("language"));

  var languageLinks = document.querySelectorAll(".language"); // languages set in navigation links

  var windowURL = window.location.href;
  var pageURL = windowURL.split("/")(4);

  var language = document.querySelectorAll(".language-switcher .languages a");
  for (var i = 0; i < language.length; i++) {
    lang.forEach(function (item, index) {
      if (pageURL == undefined) {
        language(index).onclick = function () {
          var path = item + "home";
          this.href = path;
        };
      } else {
        language(index).onclick = function () {
          var path = item + pageURL;
          this.href = path;
        };
      }
    });
  }

  for (var j = 0; j < languageLinks.length; j++) {
    var navURL = languageLinks(j).href;
    for (var k = 0; k < lang.length; k++) {
    if (windowURL.indexOf(lang(k)) != -1) {
      languages.forEach((el) => el.classList.remove("active"));
      languages(k).classList.add("active");
      if (navURL.indexOf(lang(k)) != -1) {
        languageLinks(j).closest("div").style.display = "block";
      } else {
        languageLinks(j).closest("div").style.display = "none";
      }
    } else {
      if (navURL.indexOf(lang(0)) != -1) {
        languages.forEach((el) => el.classList.remove("active"));
        languages(0).classList.add("active");
        languageLinks(j).closest("div").style.display = "block";
      } else {
        languageLinks(j).closest("div").style.display = "none";
      }
    }
  }
  }

  document.querySelector(".header").style.visibility = "visible";
  var active = document.querySelector(".language-switcher .active");
  active.closest(".language-switcher").prepend(active);
})();

sql server – TABLOCK hint for SELECT statements when blocking writers is not an issue

Since SELECT statements take a shared lock in contrast X and U it seems to me that using WITH(TABLOCK) in datawarehouse style queries used for reporting is the correct thing to do in order to avoid lock management and lock escalation.

I am talking about cases where data is not live production data and concurrency is not a problem. E.g. I don’t care about blocking writers by taking a shared table lock. Of course I do not want to block readers, but S locks does not block other readers.

So I guess I can formulate my question as: In a data warehouse environment should all queries not be hinted with WITH (TABLOCK)? And theoretically this should improve performance. If not, why?

Thanks

continuity – Do these statements about analysis with dual numbers make any sense?

I am reading Color for the Sciences by Jan Koenderink, and in Ch. 3 he introduces the dual number system to define the space of possible power spectra for a beam of light. However, his statements do not seem mathematically rigorous and I cannot see a way they could be made sensible.

enter image description here

enter image description here

He appears to be assuming there is a natural way to extend functions defined on the reals to the duals, but this post suggests this is impossible.

I see how the “blip function” he defines is ruled out. However, this is not the only way to extend the blip function on $mathbb R$ to the duals, and it seems one could simply define a blip function on the duals that agrees with the one on $mathbb R$ and also with his criterion for acceptable functions.

Finally, his claim at the end that the space is Hausdorff implies that there exists a topology, which he has not specified. Perhaps there is a natural topology on this space that is too obvious to state?