Web Analytics Made Easy -
StatCounter OOJS principles and good practice - CodingForum

Announcement

Collapse
No announcement yet.

OOJS principles and good practice

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • OOJS principles and good practice

    I’ve never been a real JS programmer and I’m now getting a bit more into object oriented JS as I’ve heard this is “the thing” nowadays. I’ve read this article as a primer. In one code example further down the page (under the Step 3 heading) it has this:
    Code:
    var myFeature = {
      'config' : {
        // default container is #myFeature
        'container' : $('#myFeature')
      },
      'init' : function(config) {
        …
        // create and/or cache some DOM elements
        // we'll want to use throughout the code
        myFeature.$container = myFeature.config.container;
      …
      …
    So, they create a new object property to cache another property in the init function. In my endeavors I’ve found that I tend to fall back to declaring variables inside my init function for this purpose. Does it really matter, actually?

    Also, I found that it’s sometimes hard to decide how to split up the code. Theoretically you could start with object oriented JS and then inside some function you could continue your old bad habits and write all spaghetti code. What’s the best practice there?
    For example, if I have this:
    Code:
    var obj = {
    	config: {
    		example: document.getElementById('example')
    	},
    	init: function() {
    		let exmpl = this.config.example;
    		window.addEventListener('scroll', function() {
    			// some code that refers to exmpl
    		});
    	}
    }
    is it better to move the code inside the anonymous eventlistener callback function into its own object property and call that or is it OK to have the code “inline”? The problem I’m facing is that if I move it into its own function I can’t reference the variables/properties that I’ve defined previously unless I also pass parameters to the function which feels like I’m overcomplicating things.
    Stop solving problems you don’t yet have!

  • #2
    Most of your question actually has little to do with objects, but more to do with scope and when to / not to use an anonymous function.

    This is made even more complex by your using an event listener as the example.

    Something to remember is that in JavaScript functions are also object constructors, and thus calling a function actually behaves like a "new Class" in other languages, in that any parameters and variables in that call will continue to exist.

    This is why IIFE / SIF / pick_a_name are so useful. JavaScript functions are also always scope blocks. this lets you avoid namespace conflicts in a way similar to if not possibly even superior to "namespaces" used in other languages. The reason they can be superior is that since they're anonymous / nameless they cannot be referenced, so ANYTHING you call or create inside them -- variables, functions, objectcs, etc -- are invisible to any code running outside them.

    How does this all relate to your question and anyonymous functions?

    The rule of thumb on when to use an anonymous function is how often it is going to be assigned to different objects/events. If it is only going to be used/called once, go ahead and make an anonymous function. If it's going to be ASSIGNED by an event handler to more than one object, make it a static function or object method and not anonymous.

    The problem this introduces is that your function would be global if not anonymous. The solution? Put it all in a IIFE/SIF/Whatever_you_wanna_call_em. Then your function is not in global scope, but IIFE scope.

    Or at least, I think that's what you're asking about. Honestly the code you presented reeks of "objects for nothing" or using objects where it's inappropriate/nonsensical. They type of trash I'd expect some career educator/student to advocate in their ignorance.

    Though you know me, I see that dollar sign in a codebase I automatically assume the whole approach is broken/wrong... and in this case it holds true.

    Since you're only accessing window there is no reason for it to exist more than once, so they're no reason for it to be a declarative object. Since it's window.onscroll you can go right ahead and use an anonymous function... hence this is not a job for objects at all apart from the natural fact that JavaScript functions are also objects in their own right... think of "var" or "let" inside a function as "private" in a PHP object, and "this" basically being public.

    Hence:
    Code:
    (function() {
        var config = document.getElementById('example');
        window.addEventListener('scroll', function() {
            // some code that refers to config
        }, false);
    })();
    Being the only code you need for that. You've got nothing to warrant shoving the overhead of extra object code down its gullet. Best part is ALL of the above code would be invisible to any code around it, the ultimate in eliminating code conflicts.

    I've been seeing a lot of really crappy JavaScript lately that's knee deep in 'objects for nothing" that results in double the overhead and at least 50% more code than needed. Could it be the folks who wrote these bloated wrecks are learning from the same source as you?

    Basically, trust your instincts. If it feels like you're over-complicating it, you are. Don't let some know-nothing bragging about "flexibility' and "re-usability' tell you otherwise. Whilst it's not good to treat a bullet hole with a band-aid, it's also kind of stupid to treat a splinter with a pressure bandage!

    Now, that said, almost everything in JavaScript is an object, and objects are JS' thing. Just don't go high hog when you don't need to when we're talking an interpreted loosely typed scripting language. There are plenty of legitimate uses for objects in JS since even the simplest of variables are as a point of fact accessible / castable as object... this just isn't one of them; or more specifically it is, just not in an explicitly declared manner.

    A big part of learning to use objects is learning when NOT to use them. A concept die-hard OOP fanboys never seem to wrap their heads around. They're a great solution to a lot of problems.They are NOT the be-all end-all solution which is why languages like actual Java are often hobbled, convoluted, and inefficient at some basic tasks. JUST as languages lacking objects often have to jump through hoops to do some fairly basic things. We have far too many "Uncle Red" types in this industry running around with flathead screwdrivers.

    Now to wait for some know-nothing to chime in with 50 lines of code they claim is "easier", "simpler", "more flexible" or "better for collaboration" because they are unqualified to write vanilla JS.
    Last edited by deathshadow; Mar 19, 2020, 02:08 PM.
    I'll kill you and your dreams tonight, begin new life.
    Bleed your death upon me, let your bloodline feed my youth.
    https://cutcodedown.com

    Comment


    • #3
      Oh, also if you're going to try and use objects with an 'init' use constructors, it's what they're for. Either use the old method of function() as the constructor and prototype as your mass properties/methods, or the "new"-sh Class method that drags JavaScript kicking and screaming into using "real" object methodology.

      Old way:

      Code:
      function myObject() {
          let exmpl = this.config.example;
          window.addEventListener('scroll', function() {
              // some code that refers to exmpl
          });
      }
      
      myObject.prototype = {
          config : {
              example : document.getElementById('example')
          }
      };
      
      var obj = new myObject();
      New way:

      Code:
      class myObject {
          config = {
              example : document.getElementById('example')
          };
          constructor() {
              let exmpl = this.config.example;
              window.addEventListener('scroll', function() {
                  // some code that refers to exmpl
              });
          }
      }
      
      var obj = new myObject();
      Beware of course that the new way does not exist in ANY version of IE, and that in V8 (Chrome) based browsers "Class" does not even exist unless you're in "strict" mode. Though it does always exist in node.js which is... strange.

      NOT that the property makes much if any sense since it's in the constructor which would only ever be run once, so lise the "config" property entirely... meaning you could also var instead of let allowing garbage collection to clean things up sooner.

      But really the whole idea of objects is re-usability, if the task is something you're hardcoding to only be done once, it really has no business being a full and proper object. It's just the wrong programming model for the task no matter what certain fanboys are likely to tell you.
      I'll kill you and your dreams tonight, begin new life.
      Bleed your death upon me, let your bloodline feed my youth.
      https://cutcodedown.com

      Comment


      • #4
        Oh, and side note -- the more I use the new "Class" the more and more I prefer the old way. It has a lot of the failings and illogic common to C++ style object creation. It looks nicer, but that really ends up being more of an illusion than reality.
        I'll kill you and your dreams tonight, begin new life.
        Bleed your death upon me, let your bloodline feed my youth.
        https://cutcodedown.com

        Comment


        • #5

          The problem this introduces is that your function would be global if not anonymous. The solution? Put it all in a IIFE/SIF/Whatever_you_wanna_call_em. Then your function is not in global scope, but IIFE scope.

          [...]

          Hence:

          Code:

          Code:
          (function() { var config = document.getElementById('example'); window.addEventListener('scroll', function() { // some code that refers to config }, false); })();
          It's worth noting that unless you need IE11 support, using JS modules is a better approach to scoping issues than an anonymous function like this.

          Quick demo:

          Code:
          <script type="module" src="script.js"></script>
          script.js
          Code:
          var config = document.getElementById('example');
          window.addEventListener('scroll', function() { // some code that refers to config }, false);

          Because it's in a module, it has its own scope so you can ignore ugly anonymous functions wrapping everything.

          And rather than having access to anything defined in other scripts, you have complete control over what external code is visible because you have to manually import it.


          myClass.js

          Code:
          function helperFunction() {
          
          }
          
          var somePrivateValue  = 1234;
          
          export default class {
              constructor(foo, bar) { }
              doSomething() {
                  return somePrivateValue;
              }
          }

          script.js

          Code:
          import MyClass from './MyClass.js';
          
          var myClass = new MyClass('foo', 'bar');
          myClass.doSomething();
          With modules you have complete control over scope. You can use `export` to export one or more classes/functions/objects/variables from one module to another but anything that is not exported is hidden from external code entirely.

          Modules solve all kinds of scoping issues, name clashes, global state and even make file organization a bit simpler.
          Last edited by Tom_B; May 26, 2020, 11:04 AM.

          Comment


          • #6

            Tom_B I dislike type="module" since it

            1) violates what the type attribute is FOR. "module" is not a huffing mime-type.

            2) relies on the HTML to determine the scope, which should be none of the HTML's bloody business.

            3) if unsupported you get no scope protection whereas IIFE works back to day one of JS' existence.

            4) Provides no mechanism for multiple blocks of isolation within one include... which if working client side you should be trying to limit the number of separate files used on a page. Creating unique scope blocks one file at a time is the antithesis of good -practice.

            5) doesn't give you the hooks for creating scope shortcuts to global properties like document and window, since if you pass them as parameters you can shorten their lookup times and shortcut them to "d" or "w". (normally I rail against the crypticness of single letter names, but it works way too well in client-side scripting.) Good enough for Google, it's good enough for me.

            It's another of the more derpy additions to JavaScript -- alongside other such mental huffing midgetry such as let / const, painfully cryptic garbage like arrow functions encouraging overuse of callbacks pissing on code clarity and performance from so on-high you'd think the almighty just got back from a kegger, and various other bits of stupidity -- that in case you couldn't tell, I'm... less than enamored of.

            So much of this chazerei reeks of being concepts people are used to from other languages that are being shoe-horned in where they don't fit, in complete ignorance of what JS is, is for, and what it's good at. It just makes me want to scream "FFS if you want to use a language that works like Java or Ruby, why the **** are you using JavaScript?"

            Of course it figures this type of thing gets added to JavaScript where it makes no sense for server side scripting (since there's "import") and is bad practice if not outright garbage code client-side ... but we still can't get this sort of thing in a language that NEEDS it like PHP where it would be an improvement. No, we still have to go full Pakled with:

            Code:
            function safeInclude($name) { include($name); }
            If we want include() to break local scope. Hurr durrz. But no, we can get that in JavaScript where it isn't even needed and could actually cause more problems than it solves. BRILLIANT!

            Hell, in terms of pointless complexity and ugly code, the example you posted using the new classes and import makes me want to go running and screaming back to IIFE. It's not clear, the code's spread out over a bunch of separate files for nothing, and it reeks of the same type of garbage that made C a pain in the *** to deal with from the day it was invented...

            But to be fair I cut my teeth on hand compiling machine language, and my first high level language was UCSD Pascal. It gives me VERY different ideas on what code clarity is, how scope should be handled, and why from those who started out in C syntax high level languages like Java, JavaScript, PHP, etc. They're all just C in a frilly dress with Mr. Winky tucked back, slipping on the CFM heels for a night on the town.
            Last edited by deathshadow; May 26, 2020, 08:28 PM.
            I'll kill you and your dreams tonight, begin new life.
            Bleed your death upon me, let your bloodline feed my youth.
            https://cutcodedown.com

            Comment


            • #7
              1) violates what the type attribute is FOR. "module" is not a huffing mime-type.
              1. For a valid reason: Old browsers which don't support modules, say "I don't understand the MIME type "module" I'm not going to try to load it. Sure, not the kind of thing you'd design up front but it makes sense why they chose to implement it that way.

              2. Specifications evolve over time. "type" does not have to be a MIME type indefinitely.

              3. Since no modern browser supports anything other than a "text/javascript" MIME type in the script tag, it's redundant and pointless to make it a MIME type since the early 2000s when you stopped learning anything new.

              2) relies on the HTML to determine the scope, which should be none of the HTML's bloody business.
              What? You load one module which has HTML scope, the rest are isolated. This is much better than standard scripts which are all given global scope and can easily step on each other's feet unless you actively program around this obvious negative aspect of the language. Hence modules solve the problem. Two files create a variable called `foo`? No problem! Just as it should be.

              But you struggled with this concept when it came to PHP namespaces as well so I'm not surprised that you don't get it.

              4) Provides no mechanism for multiple blocks of isolation within one include... which if working client side you should be trying to limit the number of separate files used on a page. Creating unique scope blocks one file at a time is the antithesis of good -practice.
              HTTP2 solves this but since it's an invention of the last 10 years you won't be aware of what it does or how it works and will claim it's pointless.


              5) doesn't give you the hooks for creating scope shortcuts to global properties like document and window
              Good. Let's try to get people avoiding programming practices that will come back and bite them on the ***. Sure it can be convenient but global state is one of the easiest ways new developers end up writing brittle code. There are always better alternatives than global state (See our previous discussion about your so called "singleton")

              "FFS if you want to use a language that works like Java or Ruby, why the **** are you using JavaScript?"
              If you don't know the answer to that then you shouldn't be in this business. Hint: We need to code in a language the browser actually understands.

              And to the contrary, it's a **good thing** that JS is finally adopting some standards that make the language more sane. IIFEs were always a workaround for the limitations of the language. It's good that those limitations are being removed. They were always a kludge to fix scoping issues because it was the only way to (sort of) isolate scope. Then we had to have `let` as well to get proper isolation, which again, was a bit of a workaround rather than a fix. Thankfully we now have a robust solution that's easy to use and solves these issues.

              If we want include() to break local scope. Hurr durrz. But no, we can get that in JavaScript where it isn't even needed and could actually cause more problems than it solves. BRILLIANT!
              What?! That's not how imports in JS work at all. Everything has its own scope. Yet again we seem to be in a discussion where you're dismissing things because they're completely new to you and you haven't even seen them before you got into a discussion about them.

              As for your PHP example, if you're including files that are doing more than defining a class (or a function) you're about 15 years behind the rest of the PHP world... I can't remember the last time I wrote more than one include/require statemet per project...

              It's not clear, the code's spread out over a bunch of separate files for nothing, and it reeks of the same type of garbage that made C a pain in the
              Let's see:

              1. The import statements make it clear exactly which file contains the code I'm looking for if I want to look at a function or class definition. If I'm using old school JS it's a complete guessing game as it could be in literally any of the files loaded on the page... or in the HTML document.

              2. One file per class helps organize the code, makes it easier to test and move between projects. If you can't see why this is beneficial then there's no point discussing it with you. 5000 line files are not fun to work with.

              Last edited by Tom_B; May 29, 2020, 06:13 PM.

              Comment


              • #8
                Originally posted by Tom_B View Post
                1. For a valid reason: Old browsers which don't support modules, say "I don't understand the MIME type "module" I'm not going to try to load it. Sure, not the kind of thing you'd design up front but it makes sense why they chose to implement it that way.
                Which would almost make sense, if the entire concept made any sense.

                Originally posted by Tom_B View Post
                2. Specifications evolve over time. "type" does not have to be a MIME type indefinitely.
                So come up with some new attribute or tag for it, instead of pissing on what little of the specification remains that ACTUALLY resembles a specification. Assuming one can even call this current "documentative" train wreck a specification where anything "authoritative" has been stamped out as if it were heresy. How DARE a specification be made authoritative. (BARF)

                But what can one expect when the specification defining the language for writing websites is written for people who make browsers, and not the people who make websites. Especially with the train wreck of ignorance, incompetence, and ineptitude the WhatWG brought to the table. Bad enough it reads like legalese written by a Finnish symphonic metal composer that was translated to Russian by a Japanese person, then Google translated to English. Let us sound a human paean, come on in the fire's warm, burn the rope and dance some more...

                Look no further than what's meant by an "empty" tag -- where <div></div> is not "empty" -- or the use of the word "deprecated" as it we're talking down in a condescending tone to the old tags like they were insolent children. Don't even get me started about how people defend how forgiving the language is, a relic of the fact that 150 and 300 baud communications often lacked parity bits. (seriously, 7n1 on Wang and DEC hardware was dumbass. Spend the extra flipping bit! would have been better off sticking with 6O1 of the sixbit era mapping in a SI/SO.)

                But then that's why the *nix command line and C language remain pointlessly and aggravatingly cryptic as if DESIGNED to teach programmers to make errors... but again, I'm a Wirth language guy who if I could, I'd be using ADA. How the HELL did C syntax become the most popular one? Wah wah, eye dunz wunna tie-p?

                Originally posted by Tom_B View Post
                3. Since no modern browser supports anything other than a "text/javascript" MIME type in the script tag
                Assuming they obey it at all... see IE7/earlier and FF14/earlier which just flat out ignore the attribute altogether. One of the FEW things I praise HTML 5 for is making it optional. See how the JS template crap goes bits-up face-down in anything prior to IE9. (though admittedly, I've stopped sending JS or CSS to IE9/earlier. It's a good breakpoint being the last version to support IE CC's... they can make do with the fully working semantic markup since style and scripting should be OPTIONAL on any well written content-driven site!)

                Originally posted by Tom_B View Post
                it's redundant and pointless to make it a MIME type since the early 2000s when you stopped learning anything new.
                Funny since most of this crap feels to me like dragging everything back to the WORST of 1990's practices.

                Originally posted by Tom_B View Post
                What? You load one module which has HTML scope, the rest are isolated. This is much better than standard scripts which are all given global scope and can easily step on each other's feet unless you actively program around this obvious negative aspect of the language.
                And this module nonsense isn't actively programming around it? :/ Much less is IIFE are so "negative an aspect" or such an outdated technique, why were they just added amongst other actual improvements in PHP 7? You'd almost think even they were starting to think namespaces were crap... since they're inherently no more or less global than the singleton model, classes, functions, or anything else.

                And because of course it's so bad they just had to add it to PHP within the past few years.

                Originally posted by Tom_B View Post
                Hence modules solve the problem. Two files create a variable called `foo`? No problem! Just as it should be.
                A problem that was already addressed CLEANER and in the correct place -- in the scripting -- by IIFE.

                Originally posted by Tom_B View Post
                HTTP2 solves this
                Given that push is diminishing returns and can have NEGATIVE impacts past the first few files (since it actually REMOVES parallelization), and given how it can also cause issues with the caching models, it's not the be-all end-all answer. You end up with one of these derpy codebases with two to four dozen separate script files you're right back at square one!

                Remember, push SHARES a single connection. That's why you do NOT throw it at everything and why keeping the number of files pushed to 3-8 is best practice. If you push too much, you can actually end up SLOWER. This is where people often screw up profiling push on first-load only, and not looking at cached loads or subpages where it can start to negatively impact things. Much akin to the halfwitted "move the CSS into the markup to speed things up" BULL**** that Pagespeed Insights started telling people when it went from a useful tool to a marketing scam for their "service". Oh they service you alright.

                Originally posted by Tom_B View Post
                but since it's an invention of the last 10 years you won't be aware of what it does or how it works and will claim it's pointless.
                Which is a laughable statement given how much of this rubbish just recreates the WORST of pre-1998 practices in web development. Aka all the browser-wars era bloat and long-dead and abandoned langauges... stuff at least a few of us learned better than to rely on.

                But as always those who forget history...

                Originally posted by Tom_B View Post
                Good. Let's try to get people avoiding programming practices that will come back and bite them on the ***.
                How would:

                Code:
                (function(d, w) {
                })(document,window);
                "bite someone on the ***" exactly?

                Originally posted by Tom_B View Post
                Sure it can be convenient but global state is one of the easiest ways new developers end up writing brittle code.
                Which has jack all to do with what I was talking about or what I quoted. Again you're basically talking out your *** like some sort of know-nothing career educator who's never once had to deal with actual websites. It's the same BS I've heard for 20 years from client's IT guys who don't understand why they're up manure river without a means of locomotion. Aka the types of clowns I usually have to tell site owners to fire.

                FFS I'm dealing with that right now with a client; where someone who says a lot of the same idiocy you're spouting has utterly screwed them over to the point they're in COURT over it on accessibility grounds, but they're equally screwed by 1.2 megabytes of scripttardery spread out over 68 separate files on a site -- site-wide -- that doesn't need more than 4k of scripting in one file.

                Much of that being this derpy "one file per class/scope" idiocy, even more of it being the use of JS to do CSS' job like it's still 2003/earlier!

                Originally posted by Tom_B View Post
                There are always better alternatives than global state (See our previous discussion about your so called "singleton")
                Yeah, and you're so laser-focused on "teh evilz uf teh glubels" that you're missing that some things inherently need global scope. IT's not about eliminating it entirely as that's impractical; it's about reducing the number of instances to the absolute minimum. It's almost like a certain group of people right now who are so laser-focused on removing a certain dirtbag from a position of authority, they're willing to do so with just as big a slimy dirtbag.

                Hence why "namespaces" provide NOTHING that a static class or singleton do not. The namespace name is global in scope... the class name is global in scope... so what's the honking difference?!? It's just a different syntax for the same functionality!

                Originally posted by Tom_B View Post
                If you don't know the answer to that then you shouldn't be in this business. Hint: We need to code in a language the browser actually understands.
                Thing is MOST of this stuff is only useful server-side in node.js and pisses on front-end code from orbit. I guess that shouldn't surprise me though given how many JS junkies can't keep it in their damned pants, with all the endless pointless "JS for nothing". JS doing stuff HTML can do just fine on its own, JS doing CSS' job. JS doing things that are none of JS' business. JS that rather than enhance is the only means of functionality, hence lacking graceful degradation and being walking-talking WCAG violations that land companies in COURT under laws like the US ADA and UK EQA.

                MAYBE if people would stop throwing 96 to 256k of HTML at doing 32k or less' job, half a megabyte of CSS spanning a half dozen files at doing 48k or less in one file's job, and MEGABYTES of scripting spread out over several dozen files for what shouldn't even be 16k in one file of JS, they wouldn't be diving for any of this asshattery.

                Mind-numbingly dumbass ignorant incompent BS like jQuery, react, vue, bootcrap, tailwind, turdpress... Taking a leak on sane and rational coding from so on-high it hits the ground as hail.

                Originally posted by Tom_B View Post
                to (sort of) isolate scope
                Sort of?!? Ok, care to explain that statement? How are they NOT isolating scope?

                Originally posted by Tom_B View Post
                Then we had to have `let` as well to get proper isolation
                As someone who prefers -- when possible -- to practice forward declaration, LET / block level scoping struck me as a pointless addition to the language for people who clearly don't have good enough organization skills to be programming a damned thing. To me that's not even a "workaround", it's pointless extra crap.

                Since I see one more person do:

                Code:
                function() {
                  let test="something";
                My boot is going up someone's backside. You probably at least realize how silly that is.

                Originally posted by Tom_B View Post
                What?! That's not how imports in JS work at all. Everything has its own scope. Yet again we seem to be in a discussion where you're dismissing things because they're completely new to you and you haven't even seen them before you got into a discussion about them.
                No, they simply provide no functionality I would want or don't already have. That's my problem with most of these additions. I COULD see their utility in server-side programming under node.js, but even then they are painfully convoluted and reek of coming from languages that if you really want that feature, why the hell are you using JavaScript?

                But that's a LOT of the problem we're seeing right now. People are trying to use stuff that has no business client-side in their front-ends. Just look at the mental-huffing midgetry trash like React of Vue vomit up. You want that type of bloat and "Eye cans youz teh wub tweknowleggies" for a full stack crapplet like when working in Electron, fine and dandy. But using most of this crap client-side is just a waste of time, effort, bandwidth, and results in bloated hard to maintain train-wreck codebases that result in slow loading hard to use websites that agian, wet the bed from orbit.

                Originally posted by Tom_B View Post
                As for your PHP example, if you're including files that are doing more than defining a class (or a function) you're about 15 years behind the rest of the PHP world...
                On this I actually 100% agree. Damned shame 99% of the off the shelf answers to problems -- turdpress, laravel, etc -- are two decades behind the curve on that. People blindly include files that set values all the damned time. Just look at how idiotically people handle SQL credentials. Flat include files that set globals is the norm -- or worse look at Turdpress' idiotic "let's put that information into DEFINE".

                Originally posted by Tom_B View Post
                I can't remember the last time I wrote more than one include/require statemet per project...
                So you start out advocating one file per class in JS, but don't do it in PHP where it might make mroe sense? You know, like NOT loading code you're not going to use?

                Take PHP based templating (and not derpy string templating like Smarty or handlebard or the rest of that pointless idiocy) Where you'd typically have a /template/templateName/common.template.php that includes just the stuff that's common to all pages, then a /template/templateName/forms.template.php for stuff common to forms, /template/templateName/categorySummary.template.php for category summaries, /template/templateName/categoryDetails.template.php, etc, etc, etc.

                The kicker being something like the variable templateName which you'd need/want to pull from the user's database session, but need / should include at the same scope as the call. You don't want to bleed the database connection variable into the template [i](since normal morons might dick with that and/or that's where code elevations are more common -- just look at turdpress mods/plugins/extensions/whatever name for them is hot and trendy this year) -- so you'd want to include WHILE breaking scope just in case.

                That you'd only have one include -- whilst claiming multiple files helps with clarity -- is scary. Makes me wonder about what disasters your codebases are... lemme guess, no "one index to rule them all" for you? Instead you have multiple endless entry-vectors and "to hell with security?" NOT that PHP security is even a thing given you can readfile, fopen, or file_get_contents .php files... in a SCRIPTING language almost defeating the point of it being interpreted scripting.

                But you're right, GOOD well written includes SHOULD only be filled with functions and classes. Damned shame NOBODY seems to actually be doing that. Then they wonder why these various systems keep winning Pwnie awards or flood CVE with entries. (again, see turdpress)

                Originally posted by Tom_B View Post
                1. The import statements make it clear exactly which file contains the code I'm looking for if I want to look at a function or class definition. If I'm using old school JS it's a complete guessing game as it could be in literally any of the files loaded on the page... or in the HTML document.
                Or like a good little doobie you use ONE file for ONE handshake, so you aren't pissing away your connection limit or hogging your SINGLE push connect. If you REALLY insist on a slew of separate files for nothing, pre-assemble them for deployment to one file! FFS.

                Originally posted by Tom_B View Post
                2. One file per class helps organize the code, makes it easier to test and move between projects. If you can't see why this is beneficial then there's no point discussing it with you. 5000 line files are not fun to work with.
                No, it isn't... but if you're slopping 5000 lines of JavaScript at a website you're inept at best, incompetent at worst! The MOST I think -- of my own code / part of the normal site, aka not counting things like social or analytic plugins -- the most I've ever deployed on a site for scripting was 3000 lines or so, and that included a full HPGL-like to Canvas renderer. Around two-thirds of that was the image in question encoded as JSON.

                Which was done as a simple draw language like HPGL ends up 1/3rd the size of converting it to SVG, and renders faster on canvas when you need to dynamically scale it.

                If you're working with client-side code and you have enough scripttardery that a single file becomes unmanageable by way of a simple ^F then you've got too much scripting; likely have scripting doing things that are NONE of JavaScript's business; likely have zero graceful degradation for scripting off/blocked; and in all likelihood have written code that could land many companies in court.

                Don't believe me? Ask Dominos, or Beyonce, or Portugul International Bank... or half the smaller Credit Unions here in the colonies where they got shut down by the fed or forced into servitude to larger organizations (like the dirtbag predators at GSA) because of changes in both accessibility and financial policies.

                Hell you'd think these lawsuits and how both civil and criminal cases are on the uptick would be a huffing wake-up call, but no... most people still for all intents and purposes on the front-end have their cranium wedged up 1997's rectum.

                But yeah, I'm the one not keeping up to date. Of course I'm not. That's the most aggravating part of it all, is most if not all of this BS reeks of the HTML 4 "transitional" mindset... and that includes a good chunk of what the WhatWG came up with for HTML 5. In this case "transitional" literally meaning "in transition from 1997 to 1998 practices".

                I mean FFS we have clowns out there who use and advocate JavaScript for "complete" control in "mobile" hamburgers or modals! Where scripting off there's zero functionality and wasting 8 to 12k of scripting on it... As if :target or :checked aren't supported in the same browsers that support media queries. Or the derps who STILL insist on using JavaScript to control layout... and the even bigger morons who use JS to load CSS for anything more than a loading animation. (aka the ONLY place it even makes sense -- not that one should NEED a "loading animation" in the first place! Though I've had more than enough know-nothing clients insist on it thanks to their marketing turds being full of it.) Same for this nonsensical practice of controlling LAYOUT from JavaScript, again NONE of JavaScript's flipping business unless it's as a minor assist (such as CSS' derpy "you can't transition 0 height to auto").

                JS for nothing and your scripts for free... that ain't workin', that's not how you do it. Lemme tell ya, these guys are DUMB!

                But then good quality scripting -- at least client-side -- should ENHANCE an already fulling working page, not be the only means of providing functionality. A concept lost on most of the people vomiting up megabytes of scripting to do single digit kilobytes job! Or worse, things that are NONE of JavaScript's flipping business in the first place!

                If you use verbose names for things, leverage IIFE and it's FULL functionality, and are working client-side for browsers, and are actually paying attention to separations of concerns, accessibility, semantics, limitations of the medium, and a host of other good practices, the majority of new stuff being slopped in here serves ZERO legitimate purpose apart from taking an already kludge filled language and making it even more complex, cryptic, and hard to follow.

                ... and remember, that's coming from someone who still works in NASM and MASM on a regular basis. But as I used to joke, I'd sooner hand assemble 8k of RCA 1802 machine langauge than try to debug 50 lines of C code. I'm starting to feel that same way with these painfully complex convoluted JS codebases I keep coming across that reek of the people making them not knowing enough to code "hello world" much less a website.
                Last edited by deathshadow; May 30, 2020, 05:44 AM.
                I'll kill you and your dreams tonight, begin new life.
                Bleed your death upon me, let your bloodline feed my youth.
                https://cutcodedown.com

                Comment


                • #9
                  Which would almost make sense, if the entire concept made any sense.

                  The concept makes perfect sense and solves the problem of scope in a much neater way than IIFE.


                  So come up with some new attribute or tag for it, instead of pissing on what little of the specification remains that ACTUALLY resembles a specification.
                  And you missed my point in the last post. They couldn't do this as if it was a new attribute, old browsers would ignore it and try to load code they can't parse.

                  By using "type", old browsers don't load the module and new browsers do. A new attribute wouldn't allow this and would break backwards compatibility.


                  Don't even get me started about how people defend how forgiving the language is, a relic of the fact that 150 and 300 baud communications often lacked parity bits.
                  I completely agree with this. Both JS and HTML are far too forgiving. XHTML was a step in the right direction, now we're back to anything goes.

                  If browsers didn't accept invalid code it would force a higher level of coding standard across the web. As it stands you can get away with writing invalid code and because it still appears to work, people think they've got it correct.

                  I dread to think of how much time was wasted coding browsers to parse invalid code in a consistent manner.

                  But then that's why the *nix command line and C language remain pointlessly and aggravatingly cryptic as if DESIGNED to teach programmers to make errors... but again, I'm a Wirth language guy who if I could, I'd be using ADA. How the HELL did C syntax become the most popular one? Wah wah, eye dunz wunna tie-p?
                  Personally I much prefer `{` and `}` to `begin` and `end`.. (the way `is` is used is a bizarre choice as well). It's quicker to type and gives less visual clutter in the code. It's entirely subjective but given where we are now I'm not in a minority.

                  Assuming they obey it at all... see IE7/earlier and FF14/earlier which just flat out ignore the attribute altogether. One of the FEW things I praise HTML 5 for is making it optional. S
                  Depends how far back you go. I remember when IE used to support type="text/vbscript". No idea which version (or even if it ever) dropped support.

                  (though admittedly, I've stopped sending JS or CSS to IE9/earlier. It's a good breakpoint being the last version to support IE CC's... they can make do with the fully working semantic markup since style and scripting should be OPTIONAL on any well written content-driven site!)
                  How many visitors do you get even on IE11 these days? Personally I've stopped supporting IE all together, though obviously it depends on the nature of the sites you build.

                  And this module nonsense isn't actively programming around it? :/ Much less is IIFE are so "negative an aspect" or such an outdated
                  That's like saying adding proper support for functions is programming around copying/pasting code.

                  An IIFE was a way of a achieving scope in a language which made it difficult because it didn't support a clean way of doing it. Now it does.

                  And because of course it's so bad they just had to add it to PHP within the past few years.
                  PHP also supports singletons, global variables, url fopen and other bad practices. The PHP developers are buidling a general purpose language, they don't dictate how you should code.

                  I don't recall ever actually seeing anyone write an IIFE in PHP though I'm sure they exist somewhere


                  A problem that was already addressed CLEANER and in the correct place -- in the scripting -- by IIFE.
                  How the hell is

                  Code:
                  var foo = (function() {
                      //...
                      return '...';
                  })();
                  cleaner than

                  Code:
                  import foo from 'foo.js';
                  Given that push is diminishing returns and can have NEGATIVE impacts past the first few files (since it actually REMOVES parallelization), and given how it can also cause issues with the caching models, it's not the be-all end-all answer. You end up with one of these derpy codebases with two to four dozen separate script files you're right back at square one!
                  Caching is easily fixed with a cookie but if you're using that many files, modules also support dynamic loading (which loads them as they're needed) or, for larger projects you can package everything together. Go look at how jQuery works these days. Though this is overkill for most scripts.

                  Which is a laughable statement given how much of this rubbish just recreates the WORST of pre-1998 practices in web development.
                  This is where you get stuck all the time isn't it? Something was bad practice in the early 90s, in your head it's still bad practice now.

                  Things change, bad practices are bad practices because they introduce negative effects. If those are avoided by advances in the language/technology stack it's no longer a bad practice.

                  Which has jack all to do with what I was talking about or what I quoted.
                  You seemed to be talking about being able to assign properties to document and window to access them globally.

                  Your example is easy:

                  Code:
                  import foo from 'foo.js';
                  
                  foo(window, document);
                  and of course the foo function can define any argument names you like...

                  Hence why "namespaces" provide NOTHING that a static class or singleton do not. The namespace name is global in scope... the class name is global in scope... so what's the honking difference?!? It's just a different syntax for the same functionality!
                  Singletons are different to namespaces. I am not getting into this again as I covered it in detail in the last thread where you refused to listen so it's pointless covering old ground.



                  Sort of?!? Ok, care to explain that statement? How are they NOT isolating scope?
                  Because they are closures they have access to variables defined outside their scope:


                  Code:
                  var d = document;
                  
                  (function() {
                      d = 'derp';
                      //And now I just broke anything outside this scope that expects `d` to be a document reference
                  }());
                  They don't isolate scope because they always have access to variables that were created outside of the closure.

                  Now, anything outside of the clousre that relies on d being a document instance breaks (FYI: This is why `const` should be used here in place of `var`, but I agree that with proper scoping it shouldn't really be needed)

                  You can't do this with a module. When you import a module it cannot acccess/change variables defined elsewhere in the script.

                  So yeah, *sort of* isolating scope. You'll say "Well you should use the var keyword before d in the closure" and I agree but that doesn't change the fact that IIFEs don't properly isolate scope and have access to things they shouldn't.

                  But that's a LOT of the problem we're seeing right now. People are trying to use stuff that has no business client-side in their front-ends. Just look at the mental-huffing midgetry trash like React of Vue vomit up. You want that type of bloat and "Eye cans youz teh wub tweknowleggies" for a full stack crapplet like when working in Electron, fine and dandy. But using most of this crap client-side is just a waste of time, effort, bandwidth, and results in bloated hard to maintain train-wreck codebases that result in slow loading hard to use websites that agian, wet the bed from orbit.
                  Totally agree. I use NoScript and it's amazing how many websites just give a blank page with JS disabled. My biggest complaint is giving every visitor, most of which are probably using a cheap phone with a weak CPU a whole bunch of processing to do when it can likely be done once on the server and given to everyone who connects!

                  That's not to say JS moduels aren't useful for things you do actually want JavaScript for though.

                  So you start out advocating one file per class in JS, but don't do it in PHP where it might make mroe sense? You know, like NOT loading code you're not going to use?
                  Yes, and that one require statement is the audoloader. All the rest of the includes are handled by that. So I guess actually I have 2 require statements per project: one to load the autoloader and one in the autoloader to load everything else.

                  PHP uses autoloaders to load one file per class. Something similar in JavaScript would be nice but much more difficult to implement.

                  You can kind of do it with dynamic imports but it still needs the file name.

                  You don't want to bleed the database connection variable into the template
                  This doesn't happen in Smarty by the way. There are plenty of arguments against Smarty (and similar systems that mix logic and markup) but it doesn't give access to global php variables (At least it shouldn't, I haven't looked at it since the early 2000s).

                  The problem is PHP mixing concerns. Rather than separating markup from logic, they mix the HTML with PHP code and use `include` to load the template. (Or in smarty, mixing HTML code with Smarty language logic, creating its own set of problems: http://www.workingsoftware.com.au/pa...i_code_yes_you
                  ).

                  Don't do that and you don't need the `include`.

                  . If you REALLY insist on a slew of separate files for nothing, pre-assemble them for deployment to one file! FFS.
                  I'll answer you with your own quote:

                  but if you're slopping 5000 lines of JavaScript at a website you're inept at best, incompetent at worst!
                  If you have so much JS that it is too much for HTTP/2 push you're probably doing too much in the client.

                  I said 5000 lines because that's not actually unreasonable. Want to include jQuery (not that I'd recommend it these days) in your project? 10500 lines. Chart.js? 13000 lines. If you do need that many lines then of course minifying and packing them makes sense.
                  Last edited by Tom_B; May 30, 2020, 09:29 AM.

                  Comment


                  • #10
                    Originally posted by Tom_B View Post
                    The concept makes perfect sense and solves the problem of scope in a much neater way than IIFE.
                    I don't find it so at all... becuase it violates separation of concerns and doesn't let you know in the SCRIPT that's what's going on. Too many blind assumptions with a total lack of clarity.

                    Originally posted by Tom_B View Post
                    And you missed my point in the last post. They couldn't do this as if it was a new attribute, old browsers would ignore it and try to load code they can't parse.
                    Something the existing method does without pissing on the markup. FFS we just got rid of the damned attribute, and now people want it back?!?

                    Originally posted by Tom_B View Post
                    I completely agree with this. Both JS and HTML are far too forgiving. XHTML was a step in the right direction, now we're back to anything goes.
                    It both was and wasn't -- I liked the stricter rules, but since browsers still pressed on as if everything was fine anyways it ended up bringing nothing to the table. Also the mere EXISTENCE of a transitional version of it defeatured the point entirely... much less the proposals for 2.0 going full Pakled letting people make up their own tags, akin to HTML 5's halfwitted idiotic hyphenated "custom tags" that defeat the entire reason HTML even exists -- semantic meanings the UA can understand regardless of media target.

                    Originally posted by Tom_B View Post
                    If browsers didn't accept invalid code it would force a higher level of coding standard across the web. As it stands you can get away with writing invalid code and because it still appears to work, people think they've got it correct.
                    It's funny how often people DON'T realize their invalid markup is making them work harder. See how flex utterly loses it's mind in IE 10 and 11 with people running around screaming about how the implementation is broken, when what's causing the render bugs are often simple things like unclosed tags, mismatched tags, or just plain invalid HTML.

                    Originally posted by Tom_B View Post
                    Personally I much prefer `{` and `}` to `begin` and `end`.. (the way `is` is used is a bizarre choice as well). It's quicker to type and gives less visual clutter in the code. It's entirely subjective but given where we are now I'm not in a minority.
                    I find it needlessly cryptic, but then from day one of my programming experience with C sytnax I oft couldn't tell { [ ( apart. I still have issues with that to this day and would much prefer a word over a cryptic character. It's a healthy chunk of why I have a rabid dislike for "arrow functions" as I'm used to languages accepting >= and => as the same damned thing. Part of what I dislike about PHP associative arrays. Don't even get me started about UFO's.

                    Originally posted by Tom_B View Post
                    Depends how far back you go. I remember when IE used to support type="text/vbscript". No idea which version (or even if it ever) dropped support.
                    I believe it was dropped for the browser in IE9, but is available up through Chakra (edge) if you're using it as the render API for your applications.

                    Remember, things like Electron or nw.js aren't a new idea, M$ Visual languages have let you pull the stunt of using a browser engine for your application render since IE5. Which is why it was comedy gold that many anti-virus softwares used IE / Trident as their render stack. IE.... as what renders the control of AV software... Just... wow.

                    Originally posted by Tom_B View Post
                    How many visitors do you get even on IE11 these days? Personally I've stopped supporting IE all together, though obviously it depends on the nature of the sites you build.
                    The banks and public utilities I have as clients ranges 8 to 12% in their stack. The medical clinics those numbers are doubled, usually because they're clinics for poor people (mental health, parenting, etc) and not big medical facilities with more cash than brains due to price gouging.

                    The poorer the clientelle the more likely you are to see older IE versions. One client I have REQUIRES IE 5.5 support be maintained just because they have no budget for new in-house machines and are still running a bunch of Geode thin clients running CE6. Currently in talks with them to get moved over to some modern nettops running Linux. I might badmouth it as a desktop OS, but when working on the cheap it doesn't get cheaper than free OS with barebones nettops. Especially when 90% of what they'll be used for is accessing an old ASA/400 mainframe.

                    Originally posted by Tom_B View Post
                    An IIFE was a way of a achieving scope in a language which made it difficult because it didn't support a clean way of doing it. Now it does.
                    I just don't see what's so dirty about it. The syntax is clean enough, a wrapping open, the word function, the function name, a normal function block, a close of the wrap, and a call via (). What's wrong with that?

                    Originally posted by Tom_B View Post
                    The PHP developers are buidling a general purpose language.
                    They really aren't -- or at least shouldn't be. It's utterly unsuited to that task and still remains best used as nothing more than glue between data sources and markup. Trying to do "Actual compute" with it is a waste of time and effort.

                    But I say the same thing about node.js. Doesn't seem to stop anyone. People are using both now in places where an interpreted scripting language is just plain the wrong tool for the job... and why? "I don't wanna learn C/C++"? "I want cross platform" when they only ever plan on it running on *nix-likes?

                    Originally posted by Tom_B View Post
                    I don't recall ever actually seeing anyone write an IIFE in PHP though I'm sure they exist somewhere
                    It was added in PHP 7, though it's poorly documented -- despite being used internally on some library functions that are written IN PHP instead of the underlying C++. Which I think is kind of stupid to have function libraries written in the langauge itself. It's a bit like FPC's creators brag about how it self compiles.


                    Originally posted by Tom_B View Post
                    How the hell is

                    Code:
                    var foo = (function() {
                    //...
                    return '...';
                    })();
                    Why the hell are you polluting the global space by assigning it a variable? Why do you have it returning a value? Of course it pollutes the global namespace if you code it to do so!

                    Originally posted by Tom_B View Post
                    Caching is easily fixed with a cookie
                    Say WHAT? Oh, are you adding to the transfer time by checking if the cookie is set server-side and micro-managing your push? That sounds... fragile. Likely to trigger push and cache misses.

                    Originally posted by Tom_B View Post
                    but if you're using that many files, modules also support dynamic loading (which loads them as they're needed) or, for larger projects you can package everything together.
                    Which again modules isn't "ready" for client side... but yeah, package everything together on deployment is what I think I suggested there.

                    Originally posted by Tom_B View Post
                    Go look at how jQuery works these days.
                    There are insufficient expletives in the English language to express my dismay over the mind-numbingly dumbass BS that is jQuery, much less the ALLEGED "skills" of the people who created, maintain, and use it. That steaming pile of idiocy is the LAST place I'd look for an example of how to do anything quickly, efficiently, or properly. It is a blight upon the Internet and was the poster child of how NOT to build websites until HTML/CSS frameworks like Bootcrap, tailblow, and W3school's dip**** w3.css came along.

                    Everything I've ever seen done with jQuery falls into at least one of three categories:

                    1) Stuff that could be done in a fraction the code without the framework, NOT counting the size of the framework against it.

                    2) Stuff that's HTML or CSS' job.

                    3) Nonsense that has ZERO blasted business on a website in the first place.

                    Originally posted by Tom_B View Post
                    This is where you get stuck all the time isn't it? Something was bad practice in the early 90s, in your head it's still bad practice now.
                    Probably because unlike most people I'm able to learn from the mistakes of the past and would prefer NOT to repeat them? Again see front-end "frameworks" where you end up with such idiotic use of presentational classes you might as well go back to writing HTML 3.2 riddled with tables for layout, font and center tags, and all the other trash the browser makers got shoehorned into the langauge no matter how badly it pissed on the very reason HTML exists.

                    ... and why today people use ASIDE in just as presentational a manner as CENTER.

                    Originally posted by Tom_B View Post
                    Things change, bad practices are bad practices because they introduce negative effects. If those are avoided by advances in the language/technology stack it's no longer a bad practice.
                    Which is where I get lost on it, as I see no "advances" that avoid a damned thing. More often than not it's the same ill informed poorly planned idea that's only new because younglings never learned the past, their trainers never left it, and certain groups want to exploit it just to maintain their position.

                    Younglings? Sheesh, makes it sound like I want to walk into the temple "Order 66" style.

                    Originally posted by Tom_B View Post
                    You seemed to be talking about being able to assign properties to document and window to access them globally.
                    They're not GLOBAL if they're parameters of the Closure/SIF/IIFE/whatever name becomes hot and trendy for the same damn thing tomorrow.

                    Your example is MORE global, as you're putting FOO into the global stack. A far cry from:

                    Code:
                    (function(d, w) {
                    
                    })(document, window);
                    Where "d" and "w" only exist inside the SIF / IIFE / whatever and there's NOTHING added to the global stack because it doesn't need some variable / name in the global space. Hence anything outside this self instancing function cannot see them.

                    ... and in 99% of the scripting I've written the past decade and a half, there's been no real reason to do it otherwise.

                    Originally posted by Tom_B View Post
                    Singletons are different to namespaces. I am not getting into this again as I covered it in detail in the last thread where you refused to listen so it's pointless covering old ground.
                    In implementation, not in intent. The ONLY difference worth mention is one of syntax, not of function. They both put a name into the global namespace that can be used to access what's inside them, with selectivity over what variables and methods are exposed and which are not.

                    I'm shocked you can't see how alike they are.

                    [QUOTE=Tom_B;n2424524]Because they are closures they have access to variables defined outside their scope:

                    Code:
                    var d = document;
                    
                    (function() {
                    d = 'derp';
                    //And now I just broke anything outside this scope that expects `d` to be a document reference
                    }());
                    A problem solved by "var"... and a mechanism you might WANT with a SIF/IIFE when something does warrant being put into the global scope -- such as a wrapping class akin to jQuery's dip**** $... and why how JQ handles it is a bloated wreck written by people not qualified to write a single blasted line of vanilla JS.

                    Code:
                    var d = document;
                    
                    (function() {
                    var d = 'derp';
                    // and now you have a "d" that's not document, but doesn't interfere with the one outside it!
                    }());
                    NOT that one would have reason to do that in the first place since that's a garbage broken card-stacked example.

                    Code:
                    They don't isolate scope because they always have access to variables that were created outside of the closure.
                    ACCESS to globals isn't an evil, polluting the namespace is. So... you're unaware of that difference? Gah, I hate to think the hoops of fire you must have to jump through with your codebases with this noodle-doodle overkill about globals that has NOTHING to do with the ACTUAL problems of globals.

                    Since the ONLY real problem they bring is namespace collisions, which there are all these mechanisms to not just avoid them with, but provide a high degree of granularity to get around.

                    Originally posted by Tom_B View Post
                    You can't do this with a module. When you import a module it cannot acccess/change variables defined elsewhere in the script.
                    If it's something you don't want changed, why is it global? Or why not attach it to something like "window" using defineProperty?

                    Originally posted by Tom_B View Post
                    So yeah, *sort of* isolating scope. You'll say "Well you should use the var keyword before d in the closure" and I agree but that doesn't change the fact that IIFEs don't properly isolate scope and have access to things they shouldn't.
                    If the scenario you laid out actually happens, there is something seriously WRONG going on in said codebase. If it's to be immutable attach it or scope it. If it's for intercommunication it basically HAS to go into the global namespace, that's what globals are FOR. It sounds like you're using some sort of programming model where nothing is ever able to talk to anything else, and it's got to be painful as hell to work that way; and probably two to five times the code needed to do the job.

                    Originally posted by Tom_B View Post
                    I use NoScript and it's amazing how many websites just give a blank page with JS disabled.
                    ... and with the clients I've been working with the past ten years, that's a instant WCAG / ADA / EQA violation and is part of why they end up in court. React/vue in particular often end up having major sections of functionality just not work scripting off/blocked, and I end up having to tell the client that the entire mess HAS to be started over from scratch, and that their IT staff choosing these technologies means they were utterly unsuited to do their jobs.

                    Oh, the stream of endless lame excuses that come from these clowns mouths. "But millions use it!" (bandwagon fallacy); "We've used it for years, why is it a problem now?" (survivorship bias); "But these people here said it's great" (plain folks, testimonial); "It was easier" (glittering generality); "It was just like the language I already knew" (transfer); you get the idea.

                    All propaganda techniques that make it easy to peddle a bald faced lie. Lies that are the heart of the popularity of some really stupid things across society as a whole. These days all you have to do is repeat "easier" a dozen times in front of a mirror as if you were trying to summon "Bloody Mary", and people will believe it no matter how much harder it is to build and maintain, or how much more code you end up vomiting up as a result.

                    Again just look at jQuery, Bootstrap, Tailwind, React, Vue, etc, etc for proof enough of that. Systems built by people not quailified to write a single damned line of the underlying langauges, that through propaganda have deluded people into thinking it's all somehow magically "easier" when it clearly is not. Hence again how we end up with people vomiting up four to twelve dozen k of markup, half a megabyte of style in a dozen files, and megabytes of scripting spanning dozens of files -- ALL doing the job of 128k or less in three files.

                    Going back to the first lesson I learned in programming -- the less code you use, the less there is to break.

                    Originally posted by Tom_B View Post
                    My biggest complaint is giving every visitor, most of which are probably using a cheap phone with a weak CPU a whole bunch of processing to do when it can likely be done once on the server and given to everyone who connects!
                    EXACTLY!!! Especially when said functionality requires as much data and processing server-side as it would with or without the scripting anyways. I just had that a few months ago with a banking portal where their ENTIRE system of looking at account balances was ajax'ed in with jQuery -- an instant ADA violation -- but the kicker was that their server-side code was literally just building HTML that their scripting used innerHTML to slop into the markup... so why the hell not just send the bloody markup as part of the hormal page load?

                    But they did it because their site was "slow" loading it that way.... and why was it slow? Tailwind. They had 270k of HTML on a page that contained ZERO content images and 3.72k of plaintext! Why was it so big? Static CSS in the markup where it can't be cached, static scripting in the markup where it had no business being in the first place. They had endless inlined JavaScript doing document.write in the markup for things that they had to code server-side anyways...

                    I mean seriously, you want some freaking hurr-durrz in PHP, try this on for size:

                    Code:
                    <p>
                        Your balance:
                        <script type="text/JavaScript">
                            document.write("<?php
                                echo $account[$currentAccNo][$currentAcctSku]['balance'];
                            ?>");
                        </script>
                    </p>
                    Herpa-freaking-derp!!! And interestingly enough, that's inside an include() where that's the ENTIRE contents OF the include. How do these clowns get these jobs much less keep them? Oh that's right, by shoving their nose so far up the boss' backside they can taste the chain smoked menthols.

                    This is the level of stupid I deal with on jobs. Don't even get me STARTED about the PHP code from a couple years ago a client had for integrating to GoldMine, where there was this 16k fancy encode being used to send the contact e-mail client-side (durrz) that once I figured out what it actually was I was flabbergasted. It was a hard coded MD5 implementation, something PHP has out of the box. Did we mention the original coder was a VB guy? It showed.

                    But that's a massive problem we see in PHP a lot! People coming in from other languages and thinking they have to write complex convoluted functions for things that PHP already has. With PHP there are so many things that it's like "Yeah, we've got a function for that already"... and still people out of being unable to master PHP.NET's search ends up being coded brute-force.

                    A problem we see across all languages. People come in from another language and magically expect everything to work like what they already learned, and refuse to embrace the differences of the language they landed in. I admit to doing that myself when I migrated from Object Pascal and Modula to C and C++. I kept banging my head against the wall trying to make it behave like what I consider a good compiler... and it took me a couple years to realize that damn, my forehead hurts. Once I embraced that it was a different language things became so much easier.

                    continued next post... (bloody size limits)
                    I'll kill you and your dreams tonight, begin new life.
                    Bleed your death upon me, let your bloodline feed my youth.
                    https://cutcodedown.com

                    Comment


                    • #11
                      ... continued

                      ... and that's the problem with many of these additions being shoehorned into JavaScript / ECMAScript / whatever. Rather than having people embrace the difference the language is becoming needlessly and pointlessly more complex. This is visible in these codebases where people now have 50+ lines of painfully cryptic garbage that relies on dumbass trash like jQuery doing the job of ten lines of vanilla scripting.

                      It's also where being pedantic about things like globals can bite you in the backside. Eventually you need cross-section communication, and that's why globals should be used with an eye-dropper not a paint roller. It does NOT mean eliminate them entirely.

                      Particularly when many of the mechanisms -- module imports, classes, namespaces, etc -- ALSO pollute the global namespace since they require having a name. Hence where a SIF / IIFE / whatever can be a superior model, it does NOT require an associated namespace if your intent is to only have the code initiate once. Hence it being one of JAvaScript's best constructs if all you're doing is an initialize and program level block at onload, DOMDocumentReady, or even better simply loading it via <script> right before <body> (by which time the DOM should be complete). Gives you complete and proper isolation, whilst still having access to globals if you absolutely have to... which is in fact often the case, though the new data- attributes are slowly making that too a thing of the past.

                      See, I'm not entirely against new stuff. data- is great and frankly overdue. Sad people are overusing it. See mind-numbing dippery like:

                      Code:
                      <h2 data-title="This Section">This Section</h2>
                      Which is almost as dumbass as:

                      Code:
                      <form role="form">
                      ... which you also see all the damned time now. The latter being a case of people either not reading or failing to comprehend the WAI-ARIA specification. Role is for when you use the WRONG tag... in which case why does it exist and why not just use the right tag?!? Aria is some really dumbass nonsense.

                      But as you're likely well aware, it's not always the technology itself at fault, it's how people choose to use it. See all the nimrods who couldn't handle the simple "with" statement in JavaScript. In STRICT we're robbed of a tool for keeping code small and clear, because some people were too stupid to use it properly.

                      Originally posted by Tom_B View Post
                      Yes, and that one require statement is the audoloader. All the rest of the includes are handled by that. So I guess actually I have 2 require statements per project: one to load the autoloader and one in the autoloader to load everything else.
                      Auto-loaders are often not a choice for me as I use "one index to rule them all" construction when possible. One entry point and one exit point means there are things that are always included (common template), things that are optionally included by the request (the actual page / functionality being called), libraries that may or may not be included based on the request, etc, etc.

                      A bit more work and a lot more include(), but well worth it to only have one entry and exit point for user calls. Rather than every blasted call being it's own damned URI resulting in having 200 gates around the wall to defend, you have one door and one door only. Strategic choke point.

                      Originally posted by Tom_B View Post
                      PHP uses autoloaders to load one file per class.
                      Which is something I always found ugly, unclear, and somewhat sloppy. Too many blind assumptions and "where is that coming from" ending up a result whenever it's not your own codebase. Far too many programs are written as if "I'm the only one that's ever going to maintain this". Sad part is when certain dumbass frameworks use that as one of their lame excuses for even existing, when all they do is make it WORSE. (yes Codeignitor and Laravel, I'm looking at you!)

                      Or more commonly, have had their reason for existing stamped out by the improvements made both back at PHP 5.2 with PDO, or under PHP 7.

                      Originally posted by Tom_B View Post
                      Something similar in JavaScript would be nice but much more difficult to implement.
                      Oh hell no... that's the last thing the language of kludge needs is more vagaries.

                      Y
                      Originally posted by Tom_B View Post
                      ou can kind of do it with dynamic imports but it still needs the file name.
                      You say that like it's a bad thing. For clarity sake I'd rather see the file name and pathing so I have some idea when I open up other people's code where the blazes things actually are.

                      Though given again that on deployment one should likely have a monolithic script, it makes little sense to not work monolithic from the start. Just as for caching style and scripting should be served separate from the markup, so don't use the STYLE or SCRIPT tags to inline either from the START. Otherwise you're just adding unnecessary extra steps.

                      Originally posted by Tom_B View Post
                      This doesn't happen in Smarty by the way. There are plenty of arguments against Smarty (and similar systems that mix logic and markup) but it doesn't give access to global php variables (At least it shouldn't, I haven't looked at it since the early 2000s).
                      Another steaming pile of manure I would NEVER let any client of mine use. PHP already IS a templating system, that's basically what the language was created for and excels at, glueing data to markup! Running some bloated convoluted garbage "templating system" atop a templating LANGAUGE is some serious herpa-freaking-derp bull, that I've more often than not encountered taking up 20-30% of a normal scripts's execution time... and for what? People too stupid to handle writing a function using an established naming convention?

                      Originally posted by Tom_B View Post
                      The problem is PHP mixing concerns. Rather than separating markup from logic, they mix the HTML with PHP code and use `include` to load the template.
                      You mean what PHP was created for in the first place? Admittedly I like my templates to be filled with functions or classes that follow a strict naming convention, but there's nothing wrong with the approach as long as data handling is separated from output.

                      Hence why I often have functions like template_pagination that don't use globals, it accepts the data ($currentPage, $pageCount, $baseURI) and spits out the appropriate unordered list. Or template_header($title = false, $currentMenu = 'home'; $lang = 'en', $charset = 'utf-8'); that outputs everything from the DOCTYPE to the opening of the MAIN tag (or DIV equivalent). Likewise template_footer($modals = [], $scripts = []) outputting everything from the close of MAIN through to the close of HTML.

                      There is reason for logic in the template, but it's not data handling logic. None of them need or access globals because I can pass the parameters as appropriate.

                      Side note, I kind of wish PHP static classes or even non-static were mutable like JS ones are. When I first found out the hoops you had to go through to make values or classes immutable (defineProperty) in JS I thought "what a crap language" but over time I've warmed to it because it's so explicit. That's the problem in a lot of languages is that they act as if verbosity were some form of evil, and code clarity is the enemy. Just look at "rust" for a poster child on that one. It's like they took one look at C++ and went "this code is way too clear and concise, what can we do to make every program look like a IOCCC winner?"

                      But again I'm one of these old dogs who's still not convinced this is a joke:
                      https://www.gnu.org/fun/jokes/unix-hoax.html

                      Originally posted by Tom_B View Post
                      I said 5000 lines because that's not actually unreasonable. Want to include jQuery (not that I'd recommend it these days) in your project? 10500 lines. Chart.js? 13000 lines. If you do need that many lines then of course minifying and packing them makes sense.
                      Utterly and thoroughly unreasonable, and the monuments to the "3i" of web development -- ignorance, incompetence, and ineptitude -- you used as examples being proof enough of that. It's bad enough that for any "real" functionality people using jQuery end up writing two to ten times the scripting (and often markup) needed to do the job, without said ALLEGEDLY "easier" framework being 10K lines of asshat nonsense.

                      I've said it from the day I first encountered jQuery, the ONLY thing you can learn from it is how NOT to write JavaScript. Just as the only things you can learn from bootcrap, tailwind, w3.css, etc, etc, is how NOT to write HTML or CSS. But no, through propaganda, bald faced lies, and exploitation of the ignorant they've become media darlings.

                      If you 'need" those dumbass frameworks for much of anything, you've likely created a bloated slow loading train wreck of 3i.

                      Though I mentioned it already, this is my bread and butter. Going into companies and organizations where they're in court for accessibility violations or being buried by poorly written codebases, ripping out all the asshat bull like jQuery, bootstrap, react, JS for nothing, etc, etc... Dragging their sites kicking and screaming into the light. Hence my distaste if not outright disgust for "frameworks" and for many of these new techniques that are not real-world deployable client-side.

                      Hell, my own attempt at making a JavaScript helper library only reinforced how STUPID the whole idea is. and how when you have an idea of what's "good", don't let other people de-rail you with their idea of what "good" is. The next version is a clean-room re-invention JUST because I got led astray by a lot of things -- that sound like the stuff you're saying -- even though I knew better. If anything I'm violating a lot of "good practices" in this upcoming library -- like modifying and extending system objects -- and overall the whole setup is the better for it.

                      Overall though, it sounds like you've taken "avoid polluting the global namespace" and magically transformed it into "Globals are evil" even as the methods you use inherently create globals... but then still piss and moan about near identical techniques that ALSO create globals. It reminds me of how 20 years ago in HTML I mistook byte obsession for minimalism (there's a difference) a problem I see infect a lot of programmers across all languages. Or the people who turned "don't use tables for layout" into "never use tables" and heaped lie upon lie to justify said position, or even the know-nothings who turned "don't use B and I when EM and STRONG are more appropriate" into "never use B and I"... to the point we even had some clowns out there a decade plus ago spewing a bald faced LIE about how B and I were deprecated.

                      But when something as simple as the 4th or 5th grade grammar norms on which HTML was created eludes so many so-called "professionals" I shouldn't be shocked when it comes to actual programming people make stupid, irrational, nonsensical decisions based more on consumption of propaganda than actual logic and reason.

                      Oh, and @VIPStephen, sorry for the thread drift, but hey at least people are posting something. That's more than most forums on the subject of web development seem to be able to say right now.
                      Last edited by deathshadow; May 30, 2020, 08:32 PM.
                      I'll kill you and your dreams tonight, begin new life.
                      Bleed your death upon me, let your bloodline feed my youth.
                      https://cutcodedown.com

                      Comment


                      • #12
                        Something the existing method does without pissing on the markup. FFS we just got rid of the damned attribute, and now people want it back?!?
                        If we were designing the language today, all scripts would be modules and we wouldn't need an attribute to tell the browser whether we're loading a script or a module.

                        Because we're stuck needing two types of js files we need some way to tell the browser what type we're loading. It would be nicer to put this information inside the JS file, but there's no way to implement that while keeping backwards compatibility.

                        I'm not sure why type="module" is so upsetting for you.


                        I just don't see what's so dirty about it. The syntax is clean enough, a wrapping open, the word function, the function name, a normal function block, a close of the wrap, and a call via (). What's wrong with that?
                        You were literally just complaining about the ugliness of nested brackets. I can tell you from experience with students that the expression `})();` is a source of confusion for new developers. You can't seriously suggest that string of 4 brackets clearly expresses what is happening.

                        Why the hell are you polluting the global space by assigning it a variable? Why do you have it returning a value? Of course it pollutes the global namespace if you code it to do so!
                        Because otherwise you do not have isolated scope between modules. You might want to create an object at one point in the code and make it available elsewhere (you can do this with callbacks too, but it's a rather long winded solution in comparison).

                        If everything is in the same IIFE then all you've done is effectively made the IIFE global scope. All the problems with global scope have just been moved into the IIFE.

                        Which is where modules come in. The are basically like having multiple IIFEs, each with the ability to export objects they want to be available elsewhere (function definitions, classes, data, etc). But the developer has to explicitly export something if they want it to be accessible outside the isolated module scope.


                        Say WHAT? Oh, are you adding to the transfer time by checking if the cookie is set server-side and micro-managing your push? That sounds... fragile. Likely to trigger push and cache misses.
                        https://www.nginx.com/blog/nginx-1-1...2-server-push/

                        Adding <10 bytes to the HTTP request is not going to affect the speed of the page at all.

                        It's really simple: If no cookie is set, push the files and set the cookie. If the cookie is set, do nothing.

                        Hardly brittle. Sure if someone clears cookies they'll get the files pushed again, but they probably cleared their browser cache at the same time.

                        Everything I've ever seen done with jQuery falls into at least one of three categories:
                        Sure, but back before CSS supported animations and transitions it was a nice enough abstraction layer for doing animations without having to reinvent the wheel. And it transparently removed several annoying browser differences back when IE6-9 were still popular. There's no reason for using it now though.

                        Which is where I get lost on it, as I see no "advances" that avoid a damned thing
                        You can't teach an old dog new tricks. You seem to have stalled in about 2007 and instantly dismiss anything that's been created since then. Autoloaders, namespaces, js modules all exist for a reason and make your life as a programmer a lot easier.



                        Your example is MORE global, as you're putting FOO into the global stack.
                        You clearly still don't know how modules work. Each module has isolated scope by design. Think of each module being its own IIFE. There is nothing in the global scope there.



                        A problem solved by "var"... and a mechanism you might WANT with a SIF/IIFE when something does warrant being put into the global scope
                        Which is exactly what I said in the post. But as I also said, this doesn't change the fact that they can alter global scope and cause bugs through action at a distance.

                        Here's a perhaps more realistic example. You're using Chart.js because you don't want to reinvent the wheel and write your own charting library (Ok maybe not you, you probably dismiss anything written by someone else... any normal developer).

                        Code:
                        <script src="chart.js"></script>
                        <script src="mychart.js"></script>
                        Code:
                        (function() {
                            Chart = ['1', '2', '3'];
                            //Because chart.js created an object called Chart I can no longer use it!
                        })();
                        With modules, it's impossible to do this because they actually isolate scope.

                        Module example:

                        Code:
                        <script type="module" src="mychart.js"></script>

                        Code:
                        import Chart from './chart.js';
                        Chart = 'aaa'; //Error: Chart is read only
                        In implementation, not in intent. The ONLY difference worth mention is one of syntax, not of function. They both put a name into the global namespace that can be used to access what's inside them, with selectivity over what variables and methods are exposed and which are not.
                        You never got the difference between a collection of static functions and an object which is where you got stuck last time and showed it's futile trying to explain the difference.

                        Since the ONLY real problem they bring is namespace collisions
                        What?! That's a minor issue. The bigger issue is action at a distance: One part of the code changing values used by a different part of the code. This is the whole reason we have isolated scope.. not just because of name clashes.

                        If it's something you don't want changed, why is it global? Or why not attach it to something like "window" using defineProperty?
                        Which is yet another hacky as hell workaround for not having `const`. Yes, let's attach arbitrary objects to the window object despite them having nothing at all to do with the window that sounds completely reasonable and not confusing at all.

                        If the scenario you laid out actually happens, there is something seriously WRONG going on in said codebase. If it's to be immutable attach it or scope it. If it's for intercommunication it basically HAS to go into the global namespace, that's what globals are FOR.
                        And yet, with modules this doesn't happen! And the problem I outlined doesn't exist.

                        It's weird you're so against them. You listed a bunch of fallacies earlier, what's the fallacy called when you're against something just because it's new? Because that seems to be your motto.


                        Particularly when many of the mechanisms -- module imports, classes, namespaces, etc -- ALSO pollute the global namespace since they require having a name.
                        Modules do not pollute the global namespace. Spend 5 minutes actually looking at things before talking about them, please.

                        With modules, every module has its own scope and you have to import other modules. And you can choose the name of those modules for use in the local scope... the same module can have different names in every other module that uses it.


                        e if your intent is to only have the code initiate once. Hence it being one of JAvaScript's best constructs if all you're doing is an initialize and program level block at onload, DOMDocumentReady, or even better simply loading it via <script> right before <body> (by which time the DOM should be complete). Gives you complete and proper isolation, whilst still having access to globals if you absolutely have to
                        Which is also solved by moudles: The code in a module doesn't execute until the DOM is ready. For 99% of use-cases this removes a level of bootstrapping.

                        In a module, I can just do:

                        Code:
                        var foo = document.getElementById('foo');
                        That same code using IIFE and a standard script:

                        Code:
                        (function() {
                            document.addEventListener('DOMContentLoaded', function() {
                                var foo = document.getElementById('foo');
                            });
                        
                        })();
                        What a mess in comparison.


                        A bit more work and a lot more include(), but well worth it to only have one entry and exit point for user calls. Rather than every blasted call being it's own damned URI resulting in having 200 gates around the wall to defend, you have one door and one door only. Strategic choke point.
                        This makes zero sense. Every site I've developed since about 1999 uses a single point of entry (usually index.php) and since they've existed, uses AutoLoaders.

                        I have no idea what you're talking about as AutoLoaders only load files when they are needed. If new Foo() is never called on a particularly request, the file containing the class definition is never loaded.

                        Again, you're showing me that you're talking about something you've never even tried, or at best don't understand at all.



                        Which is something I always found ugly, unclear, and somewhat sloppy. Too many blind assumptions and "where is that coming from" ending up a result whenever it's not your own codebase.

                        Another plus for the autoloader! "Where is class Foo stored? " I'll just look at the autoloader and it tells me. And, once I've asked that question once I know the convention and can instantly answer that question for any class in the project.

                        Using arbitrary require statements throughout the project leads to a lot more of these questions unless you happen to have open the file that is including what you're looking for.

                        There is reason for logic in the template, but it's not data handling logic. None of them need or access globals because I can pass the parameters as appropriate.
                        But that's still mixing concerns. The page I linked to sums it up better than I can: http://www.workingsoftware.com.au/pa...i_code_yes_you

                        There should be *zero* logic in a temple file

                        <ul>
                        <?php foreach ($users as $user) : ?>
                        <li><?= $user->name; ?></li>
                        <?php endforeach; ?>
                        </ul>
                        Is equivalent to:

                        Code:
                        <h1 style="font-weight:bold">Title</h1>
                        as it mixes two very different concerns.

                        When I first found out the hoops you had to go through to make values or classes immutable (defineProperty) in JS
                        Thankfully, now that we have proper private properties in JS (finally without using new Symbol()), once browsers support them immutability will be easy because an object finally has completely control over its own state.


                        Comment


                        • #13
                          Originally posted by Tom_B View Post
                          I'm not sure why type="module" is so upsetting for you.
                          And I have no idea where you see any benefits or improvement to it.

                          Originally posted by Tom_B View Post
                          You were literally just complaining about the ugliness of nested brackets.
                          That's an aspect of the language syntax, not the structure.

                          Originally posted by Tom_B View Post
                          I can tell you from experience with students that the expression `})();` is a source of confusion for new developers.
                          EVERYTHING is a source of confusion for new developers. If you can't explain what a closure is, how to apply them, and what an invokation is to them, they're not gonna get very far!

                          Originally posted by Tom_B View Post
                          Because otherwise you do not have isolated scope between modules. You might want to create an object at one point in the code and make it available elsewhere (you can do this with callbacks too, but it's a rather long winded solution in comparison).
                          And yet that name or variable you assign it IS in the global scope, so WHAT'S THE HONKING DIFFERENCE?!?

                          Of course something like a library is going to be exposed to the global scope, otherwise how the hell else will you access it. But when you WANT to isolate scope to avoid namespace collisions, a IIFE does so as long as you don't derp it onto a variable.

                          Originally posted by Tom_B View Post
                          If everything is in the same IIFE then all you've done is effectively made the IIFE global scope. All the problems with global scope have just been moved into the IIFE.
                          No, you've made it it's OWN scope, where you SHOULD be able to manage things. Just as functions inside it will have their OWN scope. They are NOT in teh global scope.

                          Code:
                          (function(d) {
                              var test = d.body.firstElementChild;
                          })(document);
                          console.log(test); // undefined
                          Everything inside it is isolated to local scope. That's the POINT of it. If you assign the function to a varaible, or import with a name, or do anything with a name, YOU'RE PUTTING IT INTO GLOBAL SCOPE. JUST like how the name of a namespace in PHP is itself in global scope and operates NO differently from a static class.

                          You keep complaining about "global scope" whilst seemingly creating things IN the global scope.

                          Originally posted by Tom_B View Post
                          Adding <10 bytes to the HTTP request is not going to affect the speed of the page at all.
                          TO EVERY request from that server. Something Google penalizes you for these days and why one should try and keep excess cookies to a minimum. I usually try to limit myself to the session ID, the day/night state if any, and that's it.

                          Though offloading static content to another domain helps with that, you then can't push them.

                          You're right though, if the number of files is kept to a minimum it should be a non-issue. Now if we could just convince Google fo that.

                          Originally posted by Tom_B View Post
                          It's really simple: If no cookie is set, push the files and set the cookie. If the cookie is set, do nothing.
                          Which could trigger cache misses on devices that do a purge due to low storage space. PArt of why crazy Goog's advice about dicking with cache-control headers is so infuriating; as if there's something horrifyingly wrong with the browser defaults. And if there IS something wrong with the browser defaults, why not ride their asses instead of making site creators dick with something they shouldn't have to.


                          Originally posted by Tom_B View Post
                          Sure, but back before CSS supported animations and transitions it was a nice enough abstraction layer for doing animations without having to reinvent the wheel.
                          Even then HOW it went about it was utter ****e, and most such goofy animated crap when scripted broke usability/functionality since again, no scripting, no page functionality. It taught an entire generation of developers to tell accessibility to go plow itself.

                          Originally posted by Tom_B View Post
                          And it transparently removed several annoying browser differences back when IE6-9 were still popular.
                          Differences that shouldn't have taken more than 50 lines of code in most codebases (and that's me Mr. Scotting the figure). It makes sense to polyfill the new ECMAScript stuff, but that's not what it did and instead they just pissed out their own broken bloated implementations.

                          Much less how it works -- telling people to constantly do the equivalent of querySelectorAll every joe-damned line and then daisy-chaining together responses is such utter ****e, I cannot fathom how anyone qualified to write a single damned line of JavaScript would EVER have decided to use it by choice.

                          There's no reason for using it now though.

                          Originally posted by Tom_B View Post
                          Autoloaders, namespaces, js modules all exist for a reason and make your life as a programmer a lot easier.
                          They don't make anything "easier" for me. AT BEST they feel like people trying to shoe-horn concepts from other languages in where they don't fit. At worst they result in complex, convoluted, hard to follow codebases that are the antithesis of sane and rational practices.

                          Originally posted by Tom_B View Post
                          Think of each module being its own IIFE. There is nothing in the global scope there.
                          At which point why do we need modules?

                          Originally posted by Tom_B View Post
                          Here's a perhaps more realistic example. You're using Chart.js because you don't want to reinvent the wheel and write your own charting library (Ok maybe not you, you probably dismiss anything written by someone else... any normal developer).
                          No, I wouldn't use it because of the lack of graceful degradation, failure to leverage fallback markup, and a script that's 10 times larger than what most of the charts it creates would be as a optimized PNG or WEBP.


                          [QUOTE=Tom_B;n2424529]//Because chart.js created an object called Chart I can no longer use it![/code]
                          What's the old Marx routine? Doctor, doctor, it hurts when I do this...

                          Groucho: So don't do that.

                          If you know you're going to need "chart' what the **** are you doing using it as a variable name?!? Hurr durrz. Mein gott Ron White is SO right.

                          Originally posted by Tom_B View Post
                          With modules, it's impossible to do this because they actually isolate scope.
                          Which you then show that they don't...

                          Module example:

                          Code:
                          <script type="module" src="mychart.js"></script>

                          Code:
                          import Chart from './chart.js';
                          Chart = 'aaa'; //Error: Chart is read only
                          I can tell that we're light-years apart on how we use JavaScript, why we use it, and even what "global scope" means.

                          Besides, if Chart was to be immutable, why the hell wasn't it defined as a property in its script? If modules are so great why isn't it modularized? You're cherry picking the good from a book of evils like someone defending the ... well, I can't say what without it being a rules violation.

                          Originally posted by Tom_B View Post
                          You never got the difference between a collection of static functions and an object which is where you got stuck last time and showed it's futile trying to explain the difference.
                          Whilst you don't seem to understand what global scope is, how to isolate it, WHEN to isolate it, and when NOT to isolate it.

                          Even your own example relying UPON it to even work. I shudder to think how lost you'd be in protected mode ring-based assembly or something like ADA.

                          Originally posted by Tom_B View Post
                          What?! That's a minor issue. The bigger issue is action at a distance: One part of the code changing values used by a different part of the code. This is the whole reason we have isolated scope.. not just because of name clashes.
                          Namespace clashes are what CAUSE the huffing problem, because you have two huffing things with the same damned name! Now you sound like someone trying to treat the symptom instead of the cause!

                          Doctor: A simple evacuation of the epidural hematoma will relieve the pressure!

                          Bones: My God man, drilling holes in his head is not the answer! The artery must be repaired! Now, put away your butcher's knives and let me save this patient before it's too late!


                          The entire thing that causes your lofty silly "action at a distance" is CAUSED by namespace collisions, that's what it huffing MEANS!!! If you don't have namespace collisions, it doesn't happen!

                          Originally posted by Tom_B View Post
                          Which is yet another hacky as hell workaround for not having `const`. Yes, let's attach arbitrary objects to the window object despite them having nothing at all to do with the window that sounds completely reasonable and not confusing at all.
                          You do know that most all properties of window are in fact aliases for globals, right? HEnce why you can just alert(); instead of window.alert();

                          It's more an unfortunately named object than having anything to ACTUALLY do with the render window. (kind of like the unfortunately named "CSS 3 grid layout module" that makes people think of the dip**** pre-defined "Grid layout" crap)

                          Though the defineProperty on window I mentioned was the extreme of something I would likely NEVER have/do in my scripting in the first place.

                          Originally posted by Tom_B View Post
                          It's weird you're so against them. You listed a bunch of fallacies earlier, what's the fallacy called when you're against something just because it's new? Because that seems to be your motto.
                          Whilst you seem to be mindlessly parroting the same wild unfounded claims of improvement over things that already exist. My problem is I hate redundancies and things that people CLAIM are better but offer nothing of actual value. Change for changes sake is not improvement.

                          I love things that offer LEGITIMATE improvements, this just isn't one of them!

                          Originally posted by Tom_B View Post
                          Modules do not pollute the global namespace. Spend 5 minutes actually looking at things before talking about them, please.
                          Sorry, I said "module imports" which is what import WAS typically called. I should have just said "import" which by their very nature -- needing a NAME assigned to them -- DO get put into the namespace. That's kind of what names do.

                          hence "import Chart from './chart.js';" puts Chart onto the global namespace, at which point what's the huffing difference? The only real benefit is that you crash the scripting on access instead of overwriting it, and one VAR / LET lets you needly sidestep that anyways. (due to the scope cascade)

                          Originally posted by Tom_B View Post
                          With modules, every module has its own scope and you have to import other modules. And you can choose the name of those modules for use in the local scope... the same module can have different names in every other module that uses it.
                          Because that provides just SO much code clarity having it have different names all over the damned place. BARF!

                          Originally posted by Tom_B View Post
                          Which is also solved by moudles: The code in a module doesn't execute until the DOM is ready. For 99% of use-cases this removes a level of bootstrapping.
                          Aka something that actually already happens by the time you get to </body> which is where the DOM is effectively complete. Hence where you wrote this garbage nonseniscal card-stacked rubbish:

                          Code:
                          (function() {
                          document.addEventListener('DOMContentLoaded', function() {
                          var foo = document.getElementById('foo');
                          })();
                          My script would read:
                          Code:
                          (function(d) {
                              var foo = d.getElementById('foo');
                          })(document);
                          Document pased to 1) speed up the namespace lookup, 2) on the assumption it would be used in a real codebase more than once.

                          Because my script would be included here:

                          Code:
                          <script src="foo.js"></script>
                          </body>
                          Again, adding crap to the language that already exists. DOMContentLoaded, DOMDocumentReady, etc, etc being mostly pointless in most codebases if your scripting is worth a flying purple fish.

                          They do not provide clarity, they do not make anything easier, they mostly replicate existing functionality, and they seem to have been made to fix problems people wouldn't be having in the first damned place if they didn't have their craniums wedged up 1997's rectum!

                          Originally posted by Tom_B View Post
                          This makes zero sense. Every site I've developed since about 1999 uses a single point of entry (usually index.php) and since they've existed, uses AutoLoaders.
                          So you're basically relying on autoloading of endless spread out files rather than explicitly stating them? Oh that has to be just SO lovely for your code clarity... NOT!

                          On the whole autoloading strikes me as a horrifically bad idea. It's just garbage in terms of simplicity and clarity. I dunno, maybe I'm too much of a control freak in that I prefer to HAVE to include manually so I can see it, or even better, PREVENT it.

                          Though I'm exceedingly paranoid about multi-ring security protections against code elevations, given how painfully vulnerable to it PHP is. All these systems practicing multiple gateway / one ring protections are just so mind-numbingly dumbass.

                          Everything I've seen with autoloaders has been a convoluted mess of code stating things that MIGHT be loaded before you've even laid out a single line of ACTUAL functionality. It feels grossly inefficient and like many things I fail to see the advantages of the approach. It just feels like more code, spread out over more places, for NOTHING of value.

                          Originally posted by Tom_B View Post
                          Using arbitrary require statements throughout the project leads to a lot more of these questions unless you happen to have open the file that is including what you're looking for.
                          You mean ACTUALLY opening up in the editor the code that you're checking?!? OH MY LORDIE TEH HORRURS!!! Just how the *** else are you in there working on code?!?

                          Or is this more of the "git does my job so I can play farmville all day" type of idiocy? Where "project managers" seem to think their job is sucking up to corporate and spending all day whacking it in the office when they're not in meetings?

                          Originally posted by Tom_B View Post
                          But that's still mixing concerns.
                          HOW? If the code that generates output is seperate from the code that actually handles data, where's the mixing of concerns?

                          The idea that a template shouldn't have logic is just adding overhead for nothing, making it harder to work with and customize, and on the whole pissing on what programming even exists to do! That's why all these derpy halfwitted "string processsing" template systems people crap atop PHP are utter and complete TRASH.

                          Though maybe if people took HTML seriously instead of saying it's "easy" when they don't even know enough about it to write as single damned line of it, vomiting up two to ten times the code needed, they wouldn't be thinking that way.

                          Templates sometimes NEED logic.

                          Code:
                          echo '<title>', (
                            $pageTitle ? $pageTitle . ' - ' : ''
                          ), SITE_TITLE, '</title>';
                          Seriously, what's the point inside something simple like pagination of adding either more function calls or the ridiculous overhead of regex / other string parsing on a routine like:

                          Code:
                          $page = $currentRecord = 0;
                          do { // do so it always does at least one
                          
                              echo '
                                  <li>';
                          
                              // actual if/else instead of ternary since string addition is slower,
                              // wasteful of memory, and uglier than comma delimits on echo.
                          
                              if (++$page == $currentPage) echo '
                                      <span>', $page, '</span>';
                              else echo '
                                      '<a href="', $uriPrefix, $currentRecord, '">', $page, '</a>';
                          
                              echo '
                                  </li>';
                          
                          } while (($currentRecord += $perPage) < $totalRecords);
                          If that's "So complex" you need to break it up into pieces, or is a "violation of separation" there's something seriously huffing WRONG going on with how you're thinking about building templates.

                          Particularly when different TEMPLATES on the same system may require different logic. Hence why template systems keep ending up adding logic to them because that level of separate isn't just impractical, it's outright inefficient and can even be confusing!

                          And it's NOT equivalent to STYLE, though if your code example wasn't ineptly coded half-assed card-stacked garbage:

                          Code:
                          echo '
                              <ul>';
                          
                          foreach ($users as $user) echo '
                                  <li>', $user->name, '</li>';
                          
                          echo '
                              </ul>';
                          So it has actual code clarity, you likely wouldn't be thinking that way. Are you REALLY going to waste an entire string or massive string processing on figuring out that a UL is opened or closed?

                          NOT that said example is how it SHOULD be done if you want that degree of separation, particularly considering that having an Array of all users likely means your database code is incompetent crap.

                          Code:
                          template_userList_header();
                          while ($user = $userStmt->fetch()) template_userList_line($user);
                          template_userList_footer();
                          If you REALLY want that degree of separation. (you could make template_userList a class or namespace if desired, but no real point if your naming convention isn't crap!)

                          Though I'd probably pass $userStmt since it's the hook to the data, since again "how DARE you actually have the logic of iterating data in the template" is taking separation of concerns too far. Only concern there would be accidental (or maliciously intentional) re-use of the stmt... Something that could be avoided by extending PDO for locking statements, something I have implemented alongside named queries.

                          Though it's getting annoying how every release of PHP 7 seems to make it harder and harder to extend PDO / PDOStatement and overload its methods. End up having to bull**** variables I don't even use just to match the "required" parameter conventions. Utter garbage.

                          Funny that way, if you saw one of my codebases you'd probably be horrified at all the "logic" in the template, and thoroughly shocked at the degree of separation I have between queries and the code allowed to call them.

                          Overall I'm a firm believer that whenever possible in the vast majority of cases .php files should only have one <?php and then use echo if you want output. That way you're EXPLICITLY declaring output instead of opening/closing <?php ?> all over the damned place. About the only time I have more thasn one <?php is for header/footer includes when using PHP to rough-template a static site.

                          Code:
                          <?php
                          include('template/common.template.php');
                          template_header('Test Page');
                          ?>
                          // static page content here
                          <?php template_footer();
                          Is about the only time I do it. Just like "includes should only have classes and functions" I'm a firm believer that most of the time includes should only have ONE <?php at the top. You want output, DECLARE it instead of dropping in and out of PHP willy-nilly. If it's an include, ONE <?php at the start, no other shorttags. Same for my main() routine used to create things in their own isolated non-public scope, part of why I'm happy to have it no longer even HAVE a name,

                          I really think that PHP shorttags need to go away. Entirely. They're GARBAGE. As do these dip**** structures to allow them to be opened/closed willy-nilly like ") :" and "endforeach;". The language won't fully mature until it gets rid of "scripting" style nomenclature and focuses on what it's REALLY for. Being a hypertext pre-processor; glue between markup and data.

                          Though if they wanted to replace { and } with nothing (since it's a huffing foreach) and endforeach, I'd be a happy camper. In that way I think Worth languages would/could/should actually benefit from dropping "begin" ... of course it begins, we just said function or class or IF or what-have-you. () around if/while evaluations and BEGIN after a FUNCTION statement is as stupid as:

                          Code:
                          <!-- start main menu -->
                          <ul id="mainMenu">
                          or worse:
                          Code:
                          <!-- end navigation -->
                          </nav>
                          Part of why I keep pointing people at this older but very insightful article on IBM's Linux site:

                          https://www.ibm.com/developerworks/l...ode/index.html

                          I'm a huge fan of the "oh, NOW we're done?" part. No **** Sherlock.

                          But what do I know? I'd like to see excess () removed from around evaluations in ALL languages, something that exists just because early C compilers were too stupid to recognize that something after an IF statement or other language construct might actually be an operation and not a boolean literal. That's some serious hurr-durrz on C syntax's part. About the only time it's useful is when your evaluations are best split into multiple lines, something most "byte obsessed" C style coders never do, preferring to cram as much as possible onto a single line like they were entering an obfuscation contest.

                          Originally posted by Tom_B View Post
                          Thankfully, now that we have proper private properties in JS (finally without using new Symbol()), once browsers support them immutability will be easy because an object finally has completely control over its own state.
                          I'm not so thankful, but that's because that's exactly the type of crap I'm going into clients who are screwed over and ripping out of their websites. JUST like chart.js, JUST like this module crap, JUST like arrow functions who's mere PRESENCE crashes scripting in IE, JUST like a whole slew of other nonsense where JavaScript junkies or server-side developers can't keep it in their pants, and/or don't know enough about HTML to be working in either huffing language!
                          I'll kill you and your dreams tonight, begin new life.
                          Bleed your death upon me, let your bloodline feed my youth.
                          https://cutcodedown.com

                          Comment


                          • #14
                            So going and looking at how stuff actually works, that's a no then?

                            You have demonstrated so much ignorance of how things work here that it's painfully embarrassing that you're talking about them.


                            And yet that name or variable you assign it IS in the global scope, so WHAT'S THE HONKING DIFFERENCE?!?
                            I'm not sure why you're struggling with this simple concept so much, NO, IT IS NOT GLOBAL SCOPE. Please, please actually spend some time learning how things work before dismissing them, or worse, what you're doing, spreading false information.


                            Code:
                            //module1.js
                            import Foo from './foo.js';
                            import Module2 from './module2.js';
                            
                            console.log(Foo); // 'Object [foo]'
                            .....
                            
                            
                            //module2.js
                            console.log(Foo); //undefined
                            //...
                            There is no `Foo` in module2.js because each module has its own scope. If you don't understand this it's no wonder you're so confused.



                            So you're basically relying on autoloading of endless spread out files rather than explicitly stating them? Oh that has to be just SO lovely for your code clarity... NOT!
                            Yes. And look at how 99% of PHP projects work... if I see `new \Foo\Bar\Baz()` I know it's in the file `/lib/Foo/Bar/Baz.php` file (or whatever convention is set up by the autoloader).

                            1. It enforces a consistent naming convention for files and classes.

                            2. Classes are only required at the moment they are used

                            3. My source code is not coupled to the filesystem. I can completely restructure my file structure. For example, if I want to change all my files from ClassName.php to the very dated ClassName.inc.php or move my classes into a different directory, I can rename/move the files and amend the autoloader. Using require statements every require line has to be manually edited... ouch.

                            4. Multiple autoloaders can be registered. If I want to use someone else's code, I can set up an autoloader for third party code that loads files from a different directory.

                            But we did this before, you don't see value in something that is more flexible, less code and enforces consistency.

                            Everything I've seen with autoloaders has been a convoluted mess of code stating things that MIGHT be loaded before you've even laid out a single line of ACTUAL functionality. It feels grossly inefficient and like many things I fail to see the advantages of the approach. It just feels like more code, spread out over more places, for NOTHING of value.
                            1. If you have more than 5 require statements across your entire project, then an autoloader will be less code.

                            2. A 4 line function is loaded as the autoloader. Everything else is loaded at the time it is instantated.

                            3. If your require statements are anywhere other than the line immediately before you use a class, then you'll be loading things that aren't needed. An autoloader will not do this.

                            4. If you move your class between projects, you have to make sure all dependencies are in the exact same relative location on each project.

                            Example 1 - Inefficient: bar.php is loaded regardless of whether `doSomething()` is called

                            Code:
                            require 'bar.php';
                            class Foo {    
                                public function doSomething() {
                                    $bar = new Bar();
                                }
                            }

                            Example 2 - Efficient: Exactly the same as an autoloader, the file is loaded only immediatly before it's needed.


                            Code:
                            class Foo {
                            
                                public function doSomething() {
                                    require 'bar.php';
                                    $bar = new Bar();
                                }
                            }
                            Only now, you have to use inefficient require_once statements because you might be creating multiple Bar instances in multiple locations:

                            Example 3
                            Code:
                            class Foo {
                            
                                public function doSomething() {
                                    require_once 'bar.php';
                                    $bar = new Bar();
                                }
                            
                                public function doSomethingElse() {
                                    require_once 'bar.php';
                                    $bar = new Bar();
                                }
                            }
                            And remember, require_once/include_once is inefficient because it has to `stat` the cwd and every folder in the include_path to check that the on you're requiring is not the same as one that's already been loaded and it makes life difficult for the opcode cache, further slowing the site down.

                            Example 4, autoloaders. Does the same as

                            autoload.php
                            Code:
                            function __autoload($name) {
                                require 'lib/' . $name . '.php';
                            }
                            Code:
                            class Foo {
                                public function doSomething() {
                                    $bar = new Bar();
                                }
                            
                                public function doSomethingElse() {
                                    $bar = new Bar();
                                }
                            }
                            So of the four approaches:

                            Example 1, loads bar.php even if doSomething() is never called, you'd really still need to use require_once here, it requires extra code at the top of each file, couples the code to the filesystem (renaming a file requires changing every require line before each `new` keyword), require_once is slower because it causes unnecessary stat calls and makes the opcache less effective.

                            Example 2, won't work in real system as it would need to use require_once, requires an extra line of code before every single `new` keyword, couples the code to the filesystem (renaming a file requires changing every require line before each `new` keyword).


                            Example 3, requires an extra line of code before every single `new` keyword, couples the code to the filesystem (renaming a file requires changing every require line before each `new` keyword), require_once is slower because it causes unnecessary stat calls and makes the opcache less effective.


                            Example 4, Autoloaders: One fewer line of code before each `new` keyword, require can be used in place of require_once as autoloaders are only triggered once anyway, doesn't couple the code to the filesystem, classes are only loaded at the moment they are needed and works with the opcode cache.

                            It's impossible to be this wrong unless you're talking about something you never even tried and just dismissed because it's different to the previous approach you were using.


                            You mean ACTUALLY opening up in the editor the code that you're checking?!? OH MY LORDIE TEH HORRURS!!! Just how the *** else are you in there working on code?!?
                            Unless you have require_once everywhere a particular class is used (which is a horrible idea, see above), you'd need to look through each file in the stack and find which one required the class you're looking for.

                            Templates sometimes NEED logic.
                            Yes, but the logic does not NEED to be in the template file. HTML NEEDS styling, but the styles do not belong in the HTML document! Just because you haven't worked out how to do something doesn't mean it's impossible.

                            See https://github.com/Level-2/Transphporm

                            Using your example:

                            layout.html

                            Code:
                            <html>
                            <title>[whatever you had in SITE_TITLE]</title>
                            </html>
                            layout.tss

                            Code:
                            title[data(pageTitle)]:before {
                                content: data(pageTitle), ' - ';
                            }
                            Zero logic in the template file. In the same way CSS applies styling to the markup, TSS supplies logic to the template.

                            That means the logic can be reused on different templates, the designer deals only in HTML, any element can be written to (You don't need placeholders/variables where dynamic content will go).

                            I will post this article again because you clearly didn't read it: http://www.workingsoftware.com.au/pa...i_code_yes_you

                            Though I'd probably pass $userStmt since it's the hook to the data
                            And now your template is coupled to the database implementation. Want to reuse the template with data that's come from somewhere else? You can't!

                            This kind of separation of concerns (database and display logic) was talked about to death in the very early 2000s, I'm surprised you missed it (edit: here's one from 2003 https://www.sitepoint.com/beyond-template-engine/ )

                            <?php
                            include('template/common.template.php');
                            template_header('Test Page');
                            ?>
                            // static page content here
                            <?php template_footer();
                            ;

                            This is horrible wordpress level disorganised code. You have opening tags in the header function and closing tags in the footer function. Having opening tags and closing tags being generated in different places is a pain in the *** to work with because you can't easily see if your tags match up correctly.


                            I really think that PHP shorttags need to go away. Entirely. They're GARBAGE. As do these dip**** structures to allow them to be opened/closed willy-nilly like ") :" and "endforeach;". The language won't fully mature until it gets rid of "scripting" style nomenclature and focuses on what it's REALLY for. Being a hypertext pre-processor; glue between markup and data.
                            I agree, we need to move logic out of templates entirely.
                            Last edited by Tom_B; Jun 1, 2020, 11:44 AM.

                            Comment


                            • #15
                              Originally posted by Tom_B View Post
                              You have demonstrated so much ignorance of how things work here that it's painfully embarrassing that you're talking about them.
                              ... and again I say the exact same about you. We're so far apart on implementation and understandings that to me, it sounds like you're just parroting the same nonsensical glittering generalities I always hear with zero understanding of efficicency. It truly sounds like your workflow is the same jacked garbage that I'm always having to clean up or sack entirely for clients.

                              As evidenced by:
                              Code:
                              //module1.js
                              import Foo from './foo.js';
                              import Module2 from './module2.js';
                              
                              console.log(Foo); // 'Object [foo]'
                              Which means its' in the current scope. Therefor if you "import" in the global scope the anme "Foo" is in the global scope. JUST becuase your module2.js has its own isolated scope, does NOT change the fact that "Foo" is STILL in the scope by which it was declared.

                              If you don't understand this it's no wonder you're so confused. (back at you). Just because it doesn't exist in a new isolated block does NOT mean it's not still in the global scope rising collision elsewhere!

                              Originally posted by Tom_B View Post
                              Yes. And look at how 99% of PHP projects work...
                              I'd rather NOT given the insecure, bloated, nearly impossible to debug train wrecks that the majority of off the shelf projects seem to be. Given how utter TRASH like Laravel, CodeIgnitor, and of course Turdpress take the simplest of tasks and either piss on their own codebases from on high with programming models that don't even fit the blasted language or task (see the mental midgetry of MVC in PHP) or just plain 3i -- ignorance, incompetence, and ineptitude -- found in systems like Wordpress, looking at the big PHP projects is absolutely horrifying. These clowns aren't even qualified to write a single damned line of HTML, and I'm supposed to trust the bloated time wasting confusing methodologies they use server-side?

                              PLEASE...

                              Originally posted by Tom_B View Post
                              if I see `new \Foo\Bar\Baz()` I know it's in the file `/lib/Foo/Bar/Baz.php` file (or whatever convention is set up by the autoloader).
                              Assuming you can find the autoloader and/or the autoloader is where you expect. It does NOTHING that a normal include wouldn't provide which is why I don't see the advantage. NOT that ANY of your examples makes a lick of sense... but again I just think we're that far apart on how we look at implementing things. You don't seem to be understanding anything I'm saying and vice-versa.

                              Originally posted by Tom_B View Post
                              1. It enforces a consistent naming convention for files and classes.
                              Which if the developer isn't already doing all on their own, trying to shove it down their throat isn't gonna fix it. See the derpy new redundant HTML 5 "structural" tags for proof of that... or how HTML 4 Strict failed to get the audience to understand what it was trying to accomplish.

                              Originally posted by Tom_B View Post
                              3. My source code is not coupled to the filesystem. I can completely restructure my file structure. For example, if I want to change all my files from ClassName.php to the very dated ClassName.inc.php or move my classes into a different directory, I can rename/move the files and amend the autoloader. Using require statements every require line has to be manually edited... ouch.
                              Which if you "need" that as functionality, you've clearly failed to plan for a logical directory structure, as is so common these days. There's a reason when I see "../" in a project I automatically assume developer 3i.

                              Though I'm wondering what the blazes you'd be doing on "every line" that moving an includes location would create such woes.

                              Originally posted by Tom_B View Post
                              But we did this before, you don't see value in something that is more flexible, less code and enforces consistency.
                              Because I don't see it providing any of those things in a meaningful or improved manner. It's making it harder and more complex. PAINFULLY so.

                              Originally posted by Tom_B View Post
                              1. If you have more than 5 require statements across your entire project, then an autoloader will be less code.
                              Generally if you need require over include, there's something WRONG with your logic. The same could be said of the "load when instantated" when you still have to create the autoloader separate for that to happen, so where's the improvement? IF you create the autoloader and don't call it due to conditions, you've just made code (the autoloader) that is run but isn't even used. How is that an improvement?

                              It comes across to me as tools to molly-coddle the people who use poor to nonexistent architectural planning.

                              Originally posted by Tom_B View Post
                              4. If you move your class between projects, you have to make sure all dependencies are in the exact same relative location on each project.
                              Probably why I dislike "dependencies" beyond anything built into the langauge itself. It's just begging for "dependency hell" that again is more often than not the result of bad planning.

                              But then I far too often see people trying to blindly just "re-use" existing code where it doesn't even fit, or code that wasn't built to be modular and re-used in a re-usable fashion. They spew "don't re-invent the wheel" as they try to use a steel hoop heat-shrunk onto a wooden rim as the tire on a Zonda F.

                              Hence why it's so comical when people pull stunts like that to "Save time and work" and end up making more work for themselves in the long run. Again, see most of this framework BS and how people constantly come to forums screaming for help when it's the derpy frameworks that got them into said mess. Then out come the endless stream of lame excuses for how it's all their own fault or my fault and NEVER the frameworks or poor methodology choices fault. "But millions use _____", "Fortune 500 companies use _____", "My teacher / boss says it's fine", etc, etc, etc...

                              Almost like dealing with Apple fans where the trash engineeering decisions are always the user's fault, not Apple's. They've actually managed to brainwash their fans into honestly believing that if something goes wrong with an Apple product because of their corner-cutting, flimsty rinky half-assed "design", that it's their own fault and not the manufacturers. See "It's not a laptop, it's a macbook".

                              Framework developers, MVC in PHP developers, and just plain guys from Montana make up endles pointless excuses to defend their use of broken, nonsensical, bloated techniques in the same way. Confirmation bias and cognitive dissonance more akin to religious fanatics than anything remotely resembling logic and reason.

                              Originally posted by Tom_B View Post
                              Example 1 - Inefficient: bar.php is loaded regardless of whether `doSomething()` is called
                              Example 2 - Efficient: Exactly the same as an autoloader, the file is loaded only immediatly before it's needed.
                              etc...etc...

                              All of which reek of bad/shoddy planning... and it's comical you didn't actually include an autoloader example in your autoloader examples. Again, reeking of card-stacking bad examples and bad practices.

                              Whilst shoving everything into separate files making the filesystem, PHP, and nearly every other aspect of the software work harder.

                              Originally posted by Tom_B View Post
                              Yes, but the logic does not NEED to be in the template file. HTML NEEDS styling, but the styles do not belong in the HTML document! Just because you haven't worked out how to do something doesn't mean it's impossible.

                              See https://github.com/Level-2/Transphporm
                              ... and how the blazes is that any good for code clarity? How the devil is adding all that excess string processing efficient from a memory use or logic execution standpoint. transphporm is a POSTER CHILD for the type of idiotic bloated BS trash I'm talking about!

                              I'd sooner punch myself in the face than deal with needlessly cryptic idiocy like:

                              Code:
                              title[data(pageTitle)]:before {
                              content: data(pageTitle), ' - ';
                              }
                              Your just building markup. There is no reason from the server-side perspective to maintain that separation... unlike client side where there's a plethora of reasons like semantics being tied to accessibility, reducing the amount of bandwidth used, and what HTML is for. When generating the HTML you don't have those concerns and artificially introducing them has the OPPOSITE of the intended effect from an execution and efficiency standpoint!

                              It's taking the simplest of things -- vomiting up markup and tying data to it -- and making it cryptic, pointlessly separated, hard to debug/diagnose, and consuming far, FAR more execution time AND doubling down on the memory footprint... for ZERO benefit other than "well you maintain the separation client side so let's shoe-horn the same thing in server-side" ... COMPLETELY MISSING WHY it's done client-side at all.

                              Originally posted by Tom_B View Post
                              I will post this article again because you clearly didn't read it: http://www.workingsoftware.com.au/pa...i_code_yes_you
                              Laugh is I did read it, and it contradicts EVERY blasted thing you're defending here... making me think you didn't comprehend its message.

                              Originally posted by Tom_B View Post
                              And now your template is coupled to the database implementation. Want to reuse the template with data that's come from somewhere else? You can't!
                              Hence why I said "tempted" but wouldn't actually do it.

                              Originally posted by Tom_B View Post
                              This kind of separation of concerns (database and display logic) was talked about to death in the very early 2000s, I'm surprised you missed it (edit: here's one from 2003 https://www.sitepoint.com/beyond-template-engine/ )
                              Ah yes, ****epoint, the den of suck-ups, sycophants, and blatant scam artist dirtbags who will promote any sleazy dirtbag practice if it lets them sell another book. Don't you DARE voice any dissent around those parts.

                              I only ever had respect for TWO people over there, one is dead; the other went and **** on that with defending something (metricless line-heights) that even his own examples of which were broken trash, but he refused to acknowledge the problems even existed, and it was all somehow MY fault that his bull**** was bull****. **** them and the source they code in on.

                              ... and in fact it was idiocy like that which led to the shoe-horning of a real-time event driven programming model (MVC) being shoe-horned into a top-down linear execution langauge (PHP) where it just doens't make a lick of sense. Separation of concerns is fine and dandy, but when it comes to server-side web code MVC draws the lines in the most half-witted incompetent places... as evidenced by the bloated slow agonizing to maintain TRASH people vomit up using it.

                              Let's just say I disagree on where the lines of separation should be drawn, and why. Again to compare to HTML it's like the PROPER use of markup being that content and logical document structure dictates source-order and semantic markup, then content + structure + semantics should dictate layout, NOT the other way around. "Design" should adapt to the needs of the content, and not dictate what the content can or should be. Thus dicking around drawing pretty pictures in Photoshop as a starting point is utterly back-assward and is NOT actually design.

                              To that same end, shoving these predetermined programming models that have NOTHING to do with how PHP is even supposed to work, with predetermined architectural models that don't even correspond to what the data is into things is NOT efficient programming. It always results in a task complexity mismatch that costs time, effort, money, and pisses on the majority of projects from orbit no more or less than how people just blindly copypasta what everyone else is doing... aka running towards the cliff like a bunch of lemmings.

                              Originally posted by Tom_B View Post
                              This is horrible wordpress level disorganised code. You have opening tags in the header function and closing tags in the footer function. Having opening tags and closing tags being generated in different places is a pain in the *** to work with because you can't easily see if your tags match up correctly.
                              Code:
                              function template_header() {
                              
                              echo '<!DOCTYPE html><html><head><meta charset="utf-8">
                              <!-- meta/link/title here -->
                              </head><body>
                              
                              <h1>Site Title/Logo</h1>
                              
                              <main>';
                              } // template_header
                              
                              function template_footer() {
                              echo '
                              </main>
                              
                              <footer>Disclaimer here</footer>
                              
                              <!-- scripts here -->
                              </body></html>';
                              
                              } // template_footer
                              Oh yeah, that's REALLY SO painfully hard to work with in terms of seeing if they line up correctly... NOT! You put them in the same file, you put them back to back at the start of the common template include, and you're DONE.

                              I am curious how (or even if) your autoload mentality would handle the prospect of multi-skinning. Aka includes that have the same prototype model but different functionalities. It's a point I mentioned but I think you didn't grasp.

                              How would the difference between template/default/common.template.php and template/someOtherTemplate/common.template.php even be handled by autoloading of classes? What mechanism would you propose for dealing with that very common scenario?

                              Or would you still go with one of these idiotic trash bloated slow "template systems" just to go nuts drawing a line of separation that has no legitimate reason to exist?

                              Good gravy the hoops people will jump through to take a good idea from something else, and shove it in where it doesn't fit. I guess that's why the propaganda technique known as "transfer" is so blasted effective.
                              Last edited by deathshadow; Jun 1, 2020, 03:30 PM.
                              I'll kill you and your dreams tonight, begin new life.
                              Bleed your death upon me, let your bloodline feed my youth.
                              https://cutcodedown.com

                              Comment

                              Working...
                              X