RoboRobok
5 months ago

How to avoid repeating logic for client- and server-side?

Posted 5 months ago by RoboRobok

Let's say I create a game like Scrabble. It uses a client-side scripting to handle user interface and server-side code to store games, moves etc.

Now, I would like to let users know if their move is correct. If they place a tile on a field they weren't supposed to, the game lets them know by disabling the OK button or whatever. But the same validation takes place on server side obviously in case someone tries to use the API directly.

What are the possibilities to avoid repeating the game rules in JavaScript and PHP? Some ideas I can think of:

  1. Just validate on the server side and use Fetch/Ajax to know if the movement can be done. I don't like this idea though, because the response won't be instant.

  2. Protect the API some other way to be sure that the movement came from the client. I don't like this idea neither, because there is no 100% method and I wouldn't like to end up with screwed up games.

  3. Use Node.js to have it all in JavaScript. I'm not sure how much Node.js can be easily shared with the client-side code, but it's probably the idea that is closest to having just one codebase. I don't use Node.js, but I could consider having is as a service for this single purpose.

What do you guys think? My current approach is to just ignore the DRY principle and having my code in PHP and JS. That is not something I'm proud of though.

Please sign in or create an account to participate in this conversation.