Software Engineering Principles with Javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
We are always trying to improve on our ability to apply our skills to solve a problem. Software engineering principles have significantly helped my ability to write higher quality code. This includes testing, modularization, using OO where appropriate, etc.
Here's an example of how I achieved some modularization in my JS. Maybe it is a bad way to achieve this, but it serves as an example of what I mean and contains a few questions of its own.
framework.js
Framework = {
CurrentState : {
IsConfigurationLoaded : false,
IsCurrentConfigurationValid : false,
Configuration : undefined //undefined .. good? bad? undefined?
},
Event : {
//event lib
},
//you get the idea
}
Question:
In what ways do you apply software engineering principles to improve the readability, maintainability, and other quality attributes of your JS?
Other Related (more specific) Questions to help in answering:
I had once written a simple JS unit testing framework, which had simple asserts and a test helper method taking a lambda. What are your thoughts on unit testing javascript?
How important is defining the boundary between your code and framework?
JS is mostly used in a browser or in a website. Does this reduce/nullify certain concerns?
Do you suggest usage of Classes and OO principles?
Usage of undefined and/or null? Should it be forbidden?
Usage of try/catch? Suggested?
When do you go from JSON to classes? Do you use Util methods that operate on the data?
Usage of prototype? Suggested? What is a good case where you wouldn't use it?

in large project i tend to differ between model-, control- and view-files ([mvc-pattern][1]).
the model-file contains everything concerning data especially my class (OOP). an example for a model-file could be:
function myClass(){
//private variable
var variable=5;
//public variable
this.newVariable = 10;
function myFunction() {
//do some stuff
alert("my function");
}
//public stuff
return {
myPublicFunction: myFunction
}
}
the view-file contains everything concerning to the layout and view and the control-file is filled with the stuff concerning to data-handling. control-file uses the class declared in the model-file and works with it. so the view only needs to include the control-file and call the functions it needs for the layout.
but in general it's quite different to generalize. i like the oo-pattern and trie to use is, if it makes sense. but i have only experience with iPhone-development, so i am not able to say something concerning web dev.
[1]: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller

Related

what is the best method to bind dom events on website based on es6? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
this days i build a custom website and i use es6 classes to perform most of the js work.
as i try to keep the site fast i do not use any js framework and try to keep it vanilla.
I wonder, what should be faster and more efficient to maintain, shall i just create lots of document.addeventlistener on single js file or shall i create class for binding events and use lile:
class dom_events {
constructor() {
document.body.addEventListener('click', this.clickHandler, false );
}
clickHandler = event => {
// do stuff
document.body.removeEventListener('click', this.clickHandler);
}
}
or maybe using some "object" functions like:
var dom_events = {
bind: function(){
document.body.addEventListener('click', this.clickHandler, false );
}
}
moreover, shall i use one big file or is it better to use one js file for each module of the website?
since i'm about to bind about 500 events, i would love to hear from your knowledge and experience
From my experience, multiple js files can slow down your website because the browser sends different requests to the server. Also, if your js file is very large, then it might cause the same problem.
If you want to add multiple js files, you can use <link rel="preload" href="path to your js file..." as="script">.
If your js file is not very large, then you can use script tag in your HTML file. This reduces the load and makes your webpage faster.

Is it a bad practice to add large parts of HTML that's not required to be visible when the site loads using javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I need to have 2 popup modals in each HTML file to allow users to login and sign up, and was wondering if it was possible to simple have a common js file to add it using innerHTML or a similar method instead of typing it out in every HTML file. Would this cause any performance issues?
Neither should cause major issues with performance, especially since you're not trying to show these models until the user has interacted with the page.
You're mentioning that you would have to copy-paste this HTML chunk into every file. This would violate the DRY principle, and cause you to be left maintaining copy-pasted HTML in many different files, which is never a good thing. In this scenario, I would go for dynamically generated HTML.
If you want to dynamically generate the HTML yourself (without a templating library, etc), then I would avoid .innerHTML as much as possible - it's convenient, but it's also easy to fall into security pitfalls with it. Prefer using the Javascript built-in DOM APIs.
I personally like to use this helper function to make the DOM APIs easier to use.
function el(tagName, attrs = {}, children = []) {
const newElement = document.createElement(tagName);
for (const [key, value] of Object.entries(attrs)) {
newElement.setAttribute(key, value);
}
newElement.append(...children);
return newElement;
}
// USAGE
const customElement = el('div', { id: 'myId', class: 'myClass' }, [
el('p', {}, ['Some Text']),
el('br')
])
// The above element will get added to the body, and has the following shape:
// <div id="myId" class="myClass">
// <p>Some Text</p>
// <br>
// </div>
document.body.appendChild(customElement)
You certainly don't have to use it, do whatever floats your boat, but I just find that a helper function like that makes it easy to write HTML-looking Javascript code, without the temptation to actually use .innerHTML.
Just use it. It won't affect the performance.
it shouldn't effect performance. If anything, if the scripts loading is deferred it might improve the performance.
As for bad practice, I don't think it would be. I mean how is it any different to something like React that has a html file with a div with an id and injects the bundled react app (webpack js files) into

Best way to integrate frontend and backend without ajax or api [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I wanna use php variable in frontend framework like Vue js.
What is the best way of integration frontend and backend framework?
This is my idea, but i think there are better way to do this.
<script id = "data" >
let $user = <?= json_encode($user) ?>
</script >
Some content...
<script >
new Vue({
data: {
user: $user
},
mounted() {
$("#data"). remove ()
}
})
While 'simplicity' is wonderful, 'functionality' is also pretty critical...
Sometimes you can get by with your type of coding (use it for some things that come into the PHP file that are needed to load the page, for example), and what you have may work for this particular situation (and, no, there isn't any way I can see to make it "better"...), though most pages will need more data that is 'fluid', and you will quickly run out of projects where you can write only 'simple' code.
Learn to use ajax (it is pretty simple once you get the hang of it) and copy/paste from your own 'library' (save snippets in a place you remember - you will find MANY things you want to keep... - I keep a 'functions.php' file and over the years it has grown pretty large with great bits-n-pieces.)
Since you are using jQuery already, here's one way to do ajax... (there are others, again, study and find the way you like...)
var url = "https://theURLtoMyAjax.phpPage";
var elements = "theStuff=thatIwantToSend&someMore=somethingElse"; // this is like writing everything in the address bar - again, there are other ways...)
$.post(url, elements, function (data) {
// do all kinds of wonderful things in here!
// the 'data' is what is returned from your call, so you can use it to update data on the page, etc.
});
So, as you can see, only a couple lines of code to add Ajax and tons of things you can do once you do it, so learn it - and use it!
Happy coding!

How can I avoid filling my JavaScript code with type-checking logic when using dependency injection? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to employ SOLID principles learnt from strongly-typed languages in a Node.js application, and implement dependency injection through the constructor in my modules.
Without a compiler to help me, I've found myself impulsively writing type-checking and null-reference checking logic to make sure dependencies of the correct type are being passed in.
var _ = require('lodash');
var ExampleModule = function(dependencies) {
var app, express, http;
if(_.isUndefined(dependencies) || typeof dependencies !== 'object') {
throw new ReferenceError('No dependencies object passed to the constructor. Actually passed: ' + typeof dependencies);
}
if(_.isUndefined(dependencies.express)) {
throw new ReferenceError('The express module must be passed as the \'express\' property in the constructor.');
} else {
express = dependencies.express;
}
// Tempted to add a type check for dependencies.express here
if(_.isUndefined(dependencies.http)) {
throw new ReferenceError('The node http module must be passed as the \'http\' property in the constructor.');
} else {
http = dependencies.http;
}
// Tempted to add a type check for dependencies.http here
};
module.exports = ExampleModule;
This feels fundamentally wrong for two reasons
Constructors filled with many conditional statements; likely to increase in size as more dependencies are needed.
Many extra unit tests are written to check the type-checks and null-reference checks are working
I don't want to spend half my time maintaining type-checking logic, but I also don't want to spend half my time debugging errors when the wrong type of a dependency is passed in.
What design pattern am I missing that would solve this problem?
small, but important clarification: the SOLID "D" is not dependency injection. it is dependency inversion.
for a better understanding of SOLID as it pertains to dynamically typed languages, watch this presentation from Jim Weirich: http://confreaks.tv/videos/rubyconf2009-solid-ruby
it's about Ruby, but all the principles are the same when applied to JavaScript.
there's also my own SOLID JavaScript presentation I did a few years ago: https://sub.watchmecode.net/episode/solid-javascript-presentation/
...
your own answer talks about require as dependency injection, but this isn't correct.
the require call is a module loader, not a dependency manager. the difference is subtle, but important.
the call to require only loads code from another file. it does not supply the dependency to your other code. you have to either call the code w/ the loaded module, or use another tool such as wire.js to supply the dependency for you.
...
regarding your dependency injection question: "it depends" is the only viable answer.
i rarely use type checking like this, when dealing with the internals of my applications.
however, if you're building an API that is called from third parties, it is often necessary to do what you have done, to make sure the API is called correctly.
Consider using typescript or flow. This will allow typing checking like most strongly typed languages.
function typedCheckFunction(x: string): string{
return x
}
typedCheckFunction(5) // would error at compile time
I prefer typescript because of the support for atom, but they are mostly the same.

How many ajax files should I have? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm starting out php.
I'm wondering how many ajax files should I have. Should I have a seperate one for each operation I want to do? each query insert etc,
Or do I like send something in the data, or maybe request that ID's the request so that the server knows what to do?
Is there a good example for that?
I don't know if it matters but I'm using jQuery.
To answer your question, I personally like having as many files as possible (with fewer lines of code), but keeping related functions groupped in an object inside the same file.
For example, you could have one file called userAjax.js which contains the userAjax object:
var userAjax = {
getUserLevel : function (userId) {
$.get // blah, blah, or any ajax request
},
setUsername : function (userId, username) {
$.get // blah, blah, or any ajax request
}
};
In your app you could then use (after including the userAjax.js):
userAjax.setUsername(37, "John");
I like using this method because it keeps code structured, you do not have too much code for too little functionality. I use it in small to medium sized projects and works great :) (both for production & maintanance).
For the server-side, you could either do the same thing, or simply have a file for each command. I also like file-per-command method because if you structure your files in folders it's very easy to maintain the code (you can go directly to the function you want by navigating through the file tree). But again, for larger projects I think you should use a more OOP-approach, like having a class with many functions in a single file.
To sum it up, it all depends, mostly based on the size of the project.
Well, you can create functions for all operations what you want to do, and handle this functions with one file. Or you can create as many as want files for handling requests. If you are using some framework built on MVC architecture, you will probably use only one file (Controller) or more functions in more controllers, it is really variable, depending on usage.
There is lot of tutorials how to use PHP with AJAX. You just need only search for them.

Categories

Resources