AngularJS: Best practices - angularjs

I don't think this question is considered opinion-based since it is asking about best practices, but at the same time I don't think there are any industry standards for AngularJS best practices, so it's hard to avoid opinions in some cases. In other cases, one way of programming is clearly better than the other. I am not sure which category this question falls under.
I don't think there are any official AngularJS best practices. There are guidelines, and some people have released their own best practices, but I haven't stumbled upon an industry standard.
I have a question about how I'm organizing my modules and the code itself. It feels like I have a lot of small files and too many folders, even though I have broken down the app into common components and core features. It's still a relatively small application, but it's likely to grow.
The biggest question I have was how I should organize my submodules. Currently each submodule is broken down into various files, separating controllers, directives, and services. I was wondering if I should just define them all in one file, and then if the submodule gets too large, break it down again.
For instance, right now I have a module app.buttonToggle, with various files:
buttonToggle.app.js
angular.module('app.buttonToggle', []);
buttonToggleCtrl.js
angular.module('app.buttonToggle').controller('ButtonToggleCtrl', ButtonToggleCtrl);
function ButtonToggleCtrl() ...
...
buttonToggle.js
angular.module('app.buttonToggle').directive('buttonToggle', buttonToggle);
function buttonToggle() ...
...
Instead would it be better to combine them into one file?
buttonToggle.app.js
angular.module('app.buttonToggle', [])
.controller('ButtonToggleCtrl', function() { ... })
.directive('buttonToggle', function() { ... });
What would be the benefit of doing the latter, if any? I like how it uses less code, but is it harder to test?

I recommend using John Papa's style guide - it is what I use to help make these decisions and keep up with and potentially contribute to the best practices. It will help you with this issue. These style guides are becoming very popular to help you with your questions.
In this case, the community agrees you should have one component per file and use a task runner like gulp or grunt to package for shipping.
https://github.com/johnpapa/angular-styleguide

The main benefit here
angular.module('app.buttonToggle').controller('ButtonToggleCtrl', ButtonToggleCtrl);
is that (due to JS hoisting) controller constructor can annotated in readable manner, e.g.
ButtonToggleCtrl.$inject = ['...'];
function ButtonToggleCtrl(...) {
It isn't an issue when automatic annotation is used.
It is also a bit more convenient to debug named functions rather than anonymous ones, though Angular provides meaningful feedback on errors in all cases.
What would be the benefit of doing the latter, if any? I like how it
uses less code, but is it harder to test?
It isn't. All of module components can be tested separately irregardless of how they were defined, as long as their definitions don't contain syntactic errors.

Related

React/Redux Application to go with Typscript or Javascript

I have to do a POC for a project based on React/Redux. This application will grow later to be big and complex website.
This is important decision to take early than later I guess.
Should I go with Typescript or not. I am so confused as there are so many options these days.
Other module I will used are Material UI , React router , Thunk, Formik etc..
Thanks
Anuj
as most things in coding it's a matter of choice for you and the requirements you have
if you want more strict type checking at compile time then go with Typescript and utilise the power it gives you
but be weary there is a learning curve with it and some errors are not as clear to solve as others and it will add time to development
so it's a balancing act and you need to decide if the benefits it gives you outweigh the cost of the learning and development time
Please go ahead with Typescript.
It is suitable for applications with huge code.
Due to the static types, several IDEs are able to offer even more predictive assistance than usual (with an instance of a class and its attributes, for example).
Types have a proven ability to enhance code quality and understandability.
It is optional to assign types. You can always write a Javascript code in Typescript but the reverse is not possible.
Types make the code more readable. It helps the developer remember faster what each piece of code is supposed to do. Hence, the developer can add and change the current code faster.
Don't worry about libraries. Most libraries have a package for types as well. Eg. #types/material-ui for material-ui

Does using dependency injection in cucumber-jvm consider bad practise?

I am still very new in Cucumber-jvm/Selenium, so I am very sorry if the question sounds dumb.
Background: I'm an intern in a big company. I'm doing an automated software testing for a product. There is already an existing automated test steps. What we're going to do is to extend the project and add our own steps. The problem is almost all of the steps have kinda same hook methods. I asked a question before on how to avoid to run hook methods and a very good man said to use tags on the hook methods. That's before I found that almost all the hook methods in the previous project are kinda same. This made me think that it's not very fast/optimize because if hook methods are global then every time I run a feature file, it will just do all the hook methods that are same. After days of doing some more coding and research, I found dependency injection using picocontainer and I thought this is a good way of fixing the current issue, but I read some of articles that said dependency injection is consider a bad practice.
My question: Consider what I stated above, does using dependency injection with picocontainer in cucumber-jvm here consider bad practise? If it is, is there more good solution to this?
(Optional Background) I don't think this is important but I'm just going to include it, the hook methods that are almost 95% in every steps:
#Before
public void keepScenario(Scenario scenario){
this.scenario = scenario;
fWait = new FluentWait<WebDriver>(BrowserDriver.getCurrentDriver());
fWait.withTimeout(Duration.ofSeconds(10));
fWait.ignoring(WebDriverException.class);
}
#After
public void screenshotOnFailure(){
if (scenario.getStatus().equals("failed")) {
BrowserDriver.getScreenshot(scenario);
}
}
Dependency injection solves the problem of sharing state between multiple step definition files in a scenario. Injecting steps into other steps might be considered a bad practice, but on a whole DI itself isn't. But none of this appears to be your direct problem.
Your problem appears to be that you have multiple hooks that do the same thing. You can either remove these duplicate hooks or use a very strict way to select which features and glue you'll use (check the CucumberOptions on your runner or commandline arguments). If narrowed down to a single class, it will only use the steps and hooks in that class.
Alternatively you can just remove the duplicate hooks.

Bootstrap vs Material UI for React?

I have been using both in my projects and sometimes I find the need to use a Material UI component within a bootstrap component and the UI displays as I would expect. I have been advised though not to use this approach. Is there any reason why since both are using the grid and can be flexed?
I tend to be verbose so I'll put the concise answer up top here:
Conclusion:
Whoever said it was bad to use both might just be expressing their
opinion, in reality saying it's bad to use both really lacks context
in what you're designing. #user3770494 made a very good point- but the
point, while valid and truthy about the build size, it does depend on
the scope of the application. If it's an intraoffice application with
everyone on a fiber network local it'd all be cached in memory
anyways... but (not that you know me) I would not judge you negatively
if you mixed them together-- unless it was for a MAJOR million user
application to run on mobile (an very low devices), desktop, and other
devices around the world requiring real(ish) time updates, and
streaming dynamic content with 10000s of active users at any givin
time 24/7.
In all truth- if it's not life or death-- I'd say use both- and also
do your own. The experience of understanding more then one thing is
better then just "committing to a single solution" for personal
growth.
The rest of this reading is optional - you're welcome :)
I personally have used both in production applications (both together, and independently)... I've also done it all from scratch... (CSS is my least favorite part of job things I do - luckily I have a coworker who is great at it) Here are my thoughts:
Warning: I tend to be verbose.
Disclaimer:
As someone who likes function over form, form is an afterthought that is nit picky for clients to ask about tenuous little changes. I am going to try to leave my opinion on "how each option looks for feels" out of this as much as I can.
Also I'm looking at your question in a current choice I'm making- which is using ReactJS / create-react-app to make "demo" projects for touch screen embeaded systems- so I am going to roll out half a dozen mock programs for demos nothing that really does anytihng exactly (CCscanner, barcode scanner, gps, webcam integration, fun stuff like that). So I'm researching what will be easist for me to just commit to for this "beacuse I'm bored and got a pi3b+board for fun).
Answer:
If you have the time, dedication and resources, there is really
nothing wrong with mixing them together. But you just need to think
about the time/cost/benifit of it. DIY to make the end user happy-
even if you mix them. Totally yourself is remaking the wheel- but you
can always pull in boostrap styles etc.
The inherent risks is that if you use both- make sure you don't "Mix them" to much- because then you will always have issues with trying
to ever do version changes on either one.
I like a lot of MaterialUIs things, but I honestly dislike how a few things look (style wise by default)- functionally I like it better
then bootstrap, but at the same time, I do not like MaterialUIs React
programming style (as a purist who hates CSS But knows how important
it is- having to use !important ever ever ever ... is big big big
nonononononononon) compared to whatever way my coworkers and I use
for conventions. Not saying it's better or worse then my own
preference- but a few things about it really irk me (even if they are
done for good reasons).
Bootstrap has a lot of choices to use for- I like how it looks better, I like how it plays with ReactJS better- but there is
reactstrap vs. react-bootstrap (which is why I found your post trying
to figure which one to use for this demo thing I'm doing).
Most recently (for production projects) I do try to stick just with one but normally I'm making systems that are function over form. So
they don't really care that much about the UI elements, it's about
how to use it not make it pretty. So I stick with using a single one
just to make my job easier- and usally still override styles myself
... if the original styles piss me off. But I do not stick with one
because "It's bad form to use both" I just stick with one for that
reason mentioned above. I'd actually say if bandwidth is not an
issue- it's quality to use both- but only use the parts of them that
you actually use.
(I noticed someone once importing full jQuery when the only thing that they used from it was $.ajax (all be it a lot but still) ... I was like... is that not overkill?!) -- So if you use both and want to keep things slim- just make sure on compilation you're only importing what you're using. Pythonically I'm saying- never use import * from module (however you express that in Javascript as a concept - webpack/gulp/whomever should take care of most of that for you). Assuming you're using ES6/7 style Javascript.
I encountered this scenario recently and opted to use both but for specific tasks. With it being a responsive web app Bootstrap made the most sense to use for the layout and Material UI for the widgets (just my personal preference).
You can definitely use both but you should be aware of the following:
There will be a lot of overlap in offered features unless you take time and effort to manage it by carefully picking elements from each of those libraries. And even then you will face situations where you can't avoid overlap. This basically results in a bigger bundle.
You will have to maintain theming variables for both systems to have a consistent presentation across your app. Even then, there will be situations like where your table checkboxes look different from your form checkboxes because they are from different libraries.
You have to learn and understand both of the systems. It means sometimes it'll be harder to find what's causing a certain bug. You'll also be spending more time deciding which library to use for which component.
Overall, it's more work for you to work with two different systems and a higher chance of things looking inconsistent. That said, mixing in things like a grid system with limited theming might not be too bad.
If possible, I highly encourage you to choose one system and stick with it.
Using both will increase your production js size.
Material Ui and bootstrap both provide components with basic styles like buttons so choose one.
You can use bootsrap grid for structure only or even go with flex.

pitfalls of IIFEs with AngularJS

I have an application made with angularJS, whole application is composed of IIFEs(Immediately Invoked Function Expression). Every module, directive, controller is itself an IIFE and they are around 100s.
I want to know what is the performance pitfall when an app has so many IIFEs.
It is OK to use IIFEs with AngularJS?
How good is using libs like browserify and requirejs with AngularJS for managing the dependencies?
Can you please throw some light on this?
The question you need to ask first is whether you've got some internal parts within the IIFE that you don't want to expose to the global scope.
The whole point of creating a closure in this manner is to mimic encapsulation and avoid polluting the global scope.
The performance pitfall is not so easy to measure; I think the performance issue is negligible when you create the IIFE (don't forget you're just creating a function). One performance issue that I might think of is that when you reference a function variable form an inner function, you need to travel through the scope chain and get it from the closure object.
I would recommend you to look at patterns like module pattern, revealing module pattern etc. I personally use the revealing module pattern.
Browserify and requireJS are two libraries that implement two different specs; the commonJS and AMD respectively. These two specifications try to accommodate a functionality that is not supported by ES3 or ES5; That is a way of defining module and then loading them in specified locations.
If you want to define modules and load them synchronously in a similar manner to hose nodeJS works, you can use Browserify. In addition, Browserify allows you to use the same modules both for client-side and server-side (as long as you're using nodeJS).
On the other hand if you want to asynchronously load your modules you can go with AMD and requireJS, but you won't be able to reuse them on the back-end.
Finally, bare in mind that everything you've mentioned is not directly connected to angularJS; those are some good JavaScript practises to overcome some issues of the language itself. It can be well used whether you're working with angular or not.
I would recommend that you use either browserify or requireJS; it will benefit you in the long run. Just imagine having 100 JS files; you would need to out the manually into your html in the correct order based on the dependency graph. You can easily come across issues like race conditions where one file should have been inserted before another one.
As for the performance overhead of IIFEs, you shouldn't have any serious issues.
As another answer said, IIFEs are a good general practice, independent of AngularJS.
If you're concerned about the performance of IIFEs, go ahead and check out these performance tests on JSPerf (or write your own):
http://jsperf.com/iife-antecedents-in-js
http://jsperf.com/immediate-anonymous-function-invocation
While some ways of IIFE creation are clearly much slower than others, I wouldn't worry about the performance of IIFEs unless you're in a large loop.

Test-Driven Development in CakePHP

I'm using CakePHP 2.3 and would like to know how to properly go about building a CakePHP website using test-driven development (TDD). I've read the official documentation on testing, read Mark Story's Testing CakePHP Controllers the hard way, and watched Mark Story's Win at life with Unit testing (PDF of slides) but am still confused. I should note that I've never been very good about writing tests in any language and don't have a lot of experience with it, and that is likely contributing to my confusion.
I'd like to see a step by step walkthrough with code examples on how to build a CakePHP website using TDD. There are articles on TDD, there are articles on testing with CakePHP, but I have yet to find an in-depth article that is about both. I want something that holds my hand through the whole process. I realize this is somewhat of a tall order because, unless my Google-fu is failing me, I'm pretty sure such an article hasn't yet been published, so I'm basically asking you to write an article (or a long Stack Overflow answer), which takes time. Because this is a tall order, I plan to start a bounty on this question worth a lot of points once I'm able to in order to better reward somebody for their efforts, should anybody be willing to do this. I thank you for your time.
TDD is a bit of falacy in that it's essentially just writing tests before you code to ensure that you are writing tests.
All you need to do is create your tests for a thing before you go create it. This requires thought and analysis of your use cases in order to write tests.
So if you want someone to view data, you'll want to write a test for a controller. It'll probably be something like testViewSingleItem(), you'll probably want to assertContains() some data that you want.
Once this is written, it should fail, then you go write your controller method in order to make the test pass.
That's it. Just rinse and repeat for each use case. This is Unit Testing.
Other tests such as Functional tests and Integration tests are just testing different aspects of your application. It's up to you to think and decide which of these tests are usefull to your project.
Most of the time Unit Testing is the way to go as you can test individual parts of the application. Usually parts which will impact on the functionality the most, the "Critical path".
This is an incredibly useful TDD tutorial. http://net.tutsplus.com/sessions/test-driven-php/

Resources