How do you synchronize server-side and client-side code? - javascript

Something I've been learning (and teaching) in Software Engineering is that code duplication is the root of all evil. On the other hand, I find it quite hard to explain how this concept should be applied to the development of web apps.
Allow me to clarify... Input & data validation can be an important part of a web app. Sometimes this validation can be quite complex. For example, I worked on a puzzle editor and the validation consisted of checking whether an operation or a move was valid. Non-trivial rules then had to be checked.
Naturally, validation must be done server-side in order to ensure the consistency and quality of the stored data. However, it's a must to do validation client-side to ensure a smooth user experience.
In most instances, client-side and server-side code are written in different languages (i.e. javascript/Python), so validation code has to be written twice. However, in my only experience with GWT/Java (Java on both sides), I found that a large portion of the validation code could be reused. This seemed to make everything easier: maintenance, refactoring, debugging...
So my question to you is: how do you manage issues related to code duplication in projects where the client-side and server-side languages are different?

The way I usually handle this is to write the validation code on the server side and expose it via a web method (in .NET, similar functionality exists in most other languages) so that it can be called from javascript. As a result, you have a single method that can be called both synchronously and asynchronously from the client side and also called from the server side. This isn't applicable in every case but it's worked very well for me so far.

Typically, it's really hard to avoid duplicating the generated code, but a common approach is to use a code generator to build either the server or client side code so you only code one half of it. The most popular approach is writing the server-side common and then having the code generator build the JavaScript code for you. For instance, the language we use at my company is Coldfusion and Form-o-matic solves that problem for us. People have also approach the problem from the opposite direction by writing JavaScript which can be executed server side. I'd look for a framework that will do this for you.

A possible solution is that you abstract the actual validation in a validation description file (in XML or any other means) using a DSL. This way you only need to implement the validation engine in both client and server language and base the validations on the same description file.

Related

HTML+javascript or javascript +jsp?

Hi I'm new to dynamic web dev. I've searched this site but couldn't find anything similar.
I want to implement a password checker, for robustness and length etc. Fairly conventional. The thing is, I have 2 options: 1. embed javascript inside an HTML. 2. embed javascript inside a jsp file.
With a little preliminary research it seems that most people recommend the former, that is to go with HTML. I wanna know why? I could be completely wrong, in that case I also wanna know why?
The "how" isn't all that important, but "why".
Edit: I know this question is full of flaws (for example JSP and HTML aren't mutually exclusive) but please indulge me a little bit and tell me which scheme is more appropriate, if I want to get things done front end, in a user's browser.
Edit#2 : Sorry I did not provide any bg information: I am working on a larger project and password checker is just a part of it, the project itself is a dynamic web project relies predominantly on java, serverlet.
As you state you are new to dynamic web dev. JSP is a server side programming language Just like PHP and others. If you want to confirm password, you can use ajax to check for a match from your database and if match was found create a session and redirect your user to the logged in page. If i misunderstood your question, please try to be clear enough.
Depends on your use-case. In some cases, just the front-end is enough. In many, I would say both is better.
By putting it in the front-end/client-side (the "HTML"), you create a more user-friendly approach, since you can rapidly and continuously evaluate the users' input and give them feedback.
If the application doesn't need to be particularly robust from a security perspective, this can be plenty.
The downside of HTML only validation of any user input is that it can easily be bypassed. As a programmer, I could figure out what its doing and easily bypass any and all client-side protects. Users can also wholesale just disable JavaScript, so if your site works without JavaScript in general, they won't get any validation. This is why "security" on the client side is never a thing. Never trust the client.
Implementing it only on the back-end/server-side ("JSP"), you can lock down the security since the end-user can't bypass any of your validation. It must match the rules you set forth.
The downside to server-side is that you must send the data to the server to be analyzed, then wait for a response. While this may be fast, its still much slower than client-side.
By doing it in both, you get the best of both worlds. You get the rapid feedback for the end-user without having to send any data to the server, and you get the full protections of making sure it is properly validated on the server-side.
The downside to this of course is you have to double-up on your code, so its more effort. That's why you want to weight the pros and cons in your particular case, as there isn't a single "best" answer.
If the HTML is enough for you - why should you use .jsp?
You need .jsp for creating dynamic content and it's gonna be compiled as Servlet - do you actually need Servlet in this case?
If security is not a big concern then HTML + javascript should be fine. It will be responsive amd lead to better user experience.
If this is an external facing application on the web then as mentioned in some of the other answers go with Jsp approach.

Use javascript validation on server

In my LAMP application I am using Javascript for form validation but of course internet users can switch Javascript off in their browser so I also validate the form data on the server using a PHP function.
Does anyone know if there is some clever way to reuse my Javascript validation on the server so as to avoid writing a PHP version?
It's a little difficult to tell without knowing how you've constructed your application, but it's unlikely you'll be able to recycle your JavaScript on the server side. On the other hand, if you construct a lightweight, fast php validation tool you can use server-side validation via XHR instead of (a lot of the) JavaScript, and save yourself some redundancy the other direction.
However, that way's bound to be slower, so the best combination of user experience and security will probably come from having some redundancy in your validation.
This might be what you are looking for. It is not a javascript implementation. But this should provide all of your basic validation methods. I do not believe you would be able to find anything close to javascript unless you are using Node.js
Validator.php

How do I share javascript on the server as well the client?

Lot of the time I end up repeating the code on the server as well as the client. Example I have a registration form; validations I do for required field, email address regex are same on the both server and the client. I ideally want to write code in one place and not repeat.
If you're using express.js, take a look at the express-expose module. It seems to do what you're looking for:
expose objects, functions, modules and more to client-side js
I am going to assume that you aren't talking about a node.js application (for that take a look at either now.js or express-expose).
In these cases, what I would recommend is to do as much server side as possible, as a client can disable javascript (the is a particularly strong point when dealing with validation). You could use ajax to hit up the server, run the code there, and return in javascript.

How should I go about writing a node.js web application with both server and client side code?

I'm planning on writing a spine/backbone.js style web application which basically just transfers a large application.js file to the client's browser that communicates with the node.js backend using ajax. The problem is that I don't know how to structure such a project, since I've never seen examples of such an application. I can picture some pros and cons with different ways of doing this
Keep everything in one project folder. Both the server side and client side code resides in the same folders which means they can share resources such as form input validation and language files. This seems like a good solution, but I have no clue how I would bundle only the code that the client needs, and not the server code. Just in general I don't know how to accomplish this. If it has been done before, I would like to see some sample code, perhaps even a git repo
Create two separate projects. One for the client and one for the server. This seems a lot more simple and straight forward, but not as elegant when it comes to sharing resources. I would have to write code such as form input validation twice.
Any thoughts?
Your first situation is a very tricky scenario and I would suggest that we're not quite there yet. Some would argue that there's little reason to try to get there, as front/back ends will always be tasked with slightly and sometimes drastically different tasks. Libraries like derby show promise, but aren't quite there yet.
I discussed this recently with a friend and we came to the conclusion that perhaps the best bet for now would be to serialize models over websockets, and then ensure that the node server and client app stay in sync.
I may work on such a library, but for now I'm still developing with 2 folders and copies of models on both sides. Layout mark-up gets sent from the server, with all other content rendered client-side after receiving JSON from the server. Frankly, the amount of duplication isn't really that substantial. A little irritating but also maintains greater flexibility to grow in different directions.
This won't be a complete answer to your question, but one library that might help if you choose to pursue such an endeavour might be Browserify.
It's designed so you can use a similar require() function with a preprocessed, or on-the-fly generated from module source, js file containing many different modules. These modules can be shared with the server side through the same require() mechanism.
I don't know explicity of a Backbone implemented on the server side as a server side counter part for model sync, that would seem to be the first goal you are looking for, aloowing code that makes sense to be shared, such as models and validation, to be usefully shared.
Another thing to look at is requirejs, which uses more traditional script tag asynchronous loading f js modules, but also works within node.js aloowing the same AMD modules to a be shared between node and client code.
Was realtime required? Otherwise the Derby approach might be a little too heavy. Express.js proposes a structure where client js is separated in public folder, and provides methods to get a quick RESTful API running, which you can then access with your application.js.
I guess you could load "classic" js files from public into node via eval() too.
Things have moved much ahead now, and things like
browserify influenced coding can help us achieve this easily
there will always be some uncommon code between server and client sides, But the goal shall always be to keep all the logic code in different modules(which are later used from both environments). This is better from TDD point of view as well, also keeps your keyboard press count to lesser.
Have a look at things like this stack -
http://mindthecode.com/lets-build-an-angularjs-app-with-browserify-and-gulp/
Having said that your option1 did not seem that manageable to me, if you had the right coders coding the right code.

Interpreting and/or receiving dotNet code at run-time

Html can contain little bits of Javascript embedded in it (e.g. defined in onclick event handlers).
If I were writing an Html browser using a dotNet language like C#, what technologies or APIs could I use to run such Javascript fragments, given that I don't receive it until run-time (and receive it as string data, not as executable code)?
Is it any easier or harder if the code to be run were C# snippets rather than Javascript?
Is there any technique which doesn't require my code to have unusual priviledges? For example, a method like CodeCompiler.FromSource requires SecurityPermissionFlag.UnmanagedCode (which seems to me excessive: I don't see why it's so risky to compile code).
If I controlled the server-side as well as the client-side code, I could also consider compiling such script fragments on the server instead of on the client, and then sending it as precompiled code to the client side to be executed. Is there a way to send such code (a dotNet assembly, presumably) over the network to the client, have client-side code receive it from the network into client-side RAM, and invoke it on the client side without storing it as a file on a client-side disk drive?
Edit
I have answer to the first three questions: I've resigned myself to the fact that compiling takes high privileges. I don't see why; maybe (although I don't find this a very convincing reason) it's because the compiler is implemented using unmanaged code. Maybe this will change when they reimplement the compiler using managed code, in maybe the "C# version 5" timeframe. In any case, whatever the reason, that seems to be the way it is, and there are no work-arounds (other similar APIs but which require fewer privileges).
My remaining question then is how to get an Assembly instance from one machine to another. When I have time I'll find out whether untrusted code can run the Assembly.Load(byte[] rawAssembly) method.
Server side Javascript is one of the languages supported by the .NET platform. I used it many times in the scenrios when you need to insert small code snippets into existing code. Runtime it can be loaded from i.e. database and compiled, so there is no preformance penalty.
From the standpoint of making the plumbing work (retrieveing the source, compiling it, etc.) there is no difference. With strongly typed languages though it is much more difficult to assemble code snippets into a compilable compilation unit.
Permissions is certanly a challenge. I am not sure about the specific permission you mentioned, but security is a concern, after all the source you compile can be anything and if you are not careful about the source of your code it can become the backdoor into your system
The answer to this one is - yes of course. You can load an assembly from anywhere, not necessarily from a file, you can also compile in memory - that's what I do. There is no dll file in this case.
You're asking several questions, sort of, so I'll give you an idea on one of them.
There's a very good article and some code samples from:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
which talks about compiling and executing C# code at runtime. I found it very useful and I am using this in a standard c# application. Seems like it would be usable for your problem as well.

Categories

Resources