CodeGym /Java Course /Frontend SELF EN /Everything is Objects

Everything is Objects

Frontend SELF EN
Level 39 , Lesson 0
Available

1.1 Objects and Classes

Today you'll learn about how a typical JavaScript program is structured. And here’s the big news: every JavaScript program is made up of classes and objects. JavaScript is an object-oriented language, and everything in it is an object: numbers, strings, functions, and even classes.

So what are classes?

Let me start with an analogy. Imagine you want to build a small ship. First, you need to create a blueprint, then give it to a factory, where they’ll build the ship based on that blueprint. Or a dozen ships. As many as you want, really. The key point here is that dozens of identical ships are built from one blueprint.

It's exactly the same in JavaScript programming.

Blueprints

A programmer is like a designer. Only instead of drawing blueprints, a JavaScript programmer writes classes. Then, based on the blueprints, parts are created, and based on the classes, objects are created.

Blueprints

First, we write classes (make blueprints), and then, during the execution of the program, JavaScript creates objects based on those classes. Just like ships are built based on blueprints.

There's only one blueprint, but there can be many ships. Ships can be different, have different names, carry different cargo. But they are very similar: they are all ships with identical construction and can perform similar tasks.

Or here's another analogy...

An Ant Colony

An ant colony is a great example of object interaction. In the simplest ant colony, there are three classes of ants: queen, warriors, and worker ants.

The number of ants in each class is different. There’s one queen in the entire colony, dozens of warriors, and hundreds of worker ants. Three classes and hundreds of objects. Ants interact with each other, with the same ants and ants of other classes following strict rules.

It's just the perfect example. In a typical program, it’s exactly like that. There is a main object that creates objects for all other classes. Objects start interacting with each other and the "outside world" of the program. The behavior inside these objects is strictly programmed.

These two explanations are two sides of the same coin. The truth is in the middle. The first example (about blueprints and ships) demonstrates the relationship between a class and the objects of that class. The analogy is very strong. The second example (about the ant colony) shows the relationship between objects that exist while the program is running and the written classes.

First, you need to write classes for all the objects that exist in the program, and then describe their interactions. Sounds complicated, but it's easier than it seems.

In JavaScript, all entities during the program's execution are objects, and writing the program comes down to describing different ways objects interact. Objects simply call each other's methods and pass the necessary data into them.

Documentation

So how do you know what data to pass into methods? It's all been figured out for you.

Usually, each class comes with a description that explains what it was created for. Also, usually each public method has a description: what it does and what data needs to be passed into it.

To use a class, you need to generally understand what it does. And you need to know exactly what each of its methods does. It's not necessary to know how it does it. It's like a magic wand.

Let's take a look at some code - copying a file:

JavaScript
    
      const fs = require('fs');

      // Open files
      const src = fs.createReadStream('source.txt');
      const dst = fs.createWriteStream('destination.txt');

      // Copy contents from source.txt to destination.txt
      src.pipe(dst);

      // Close files after copying is complete
      src.on('end', () => {
        src.close();
        dst.close();
      });
    
  

If you read this code line by line, you can guess what it does in general terms. Although, it requires experience and practice. So, after some time, this code will seem familiar and understandable to you.

1.2. Program Design

Designing a program is an art. It’s both simple and complex at the same time. Simple, because there are no strict laws: whatever is not forbidden is allowed. And it's complex for the same reason: there are many ways to do something, and it’s not always easy to find the best one.

Designing a program is like writing a book. On one hand, you're just writing letters, words, sentences. On the other hand, plot matters, character development, internal conflicts, style, intrigue, and so on.

The main thing is to understand who you're writing code for. And you write for other programmers.

Developing any product involves making changes: adding here, deleting there, redoing this. And in small iterations, large, huge, and massive projects are born.

The main requirement for code is that it must be understandable to other programmers. Wrong but understandable code can be fixed. Right and obscure code can't be improved. It will just have to be thrown away.

So how do you write good, understandable code?

To do this, you need to do three things:

  • Write good, understandable code within methods — it’s the easiest
  • Decide what entities should be in the program
  • Correctly break the program into logical parts

What's behind these concepts?

Write good code within methods

If you have at least a basic level of English, you might notice how easy it sometimes is to read code — like English sentences:

  • class Cat extends Pet — the Cat class extends the Pet class
  • while (stream) — while the stream is not empty ...
  • a < b ? a : b — if a is less than b, return a, otherwise return b

This is done on purpose. JavaScript is one of the few languages where you can easily write self-documenting code: code that's understandable without comments. In good JavaScript code, many methods read simply like English sentences.

Your task when writing code is to make it as simple and concise as possible. Just think about how easy it will be for someone else to read your code, and you'll start moving in the right direction.

In JavaScript, it’s customary to write easily readable code. Ideally, each method should fit entirely on the screen (method length — 20-30 lines). This is the norm for the entire JavaScript community. If the code can be improved, it should be improved.

The best way to learn to write good code is through constant practice. Write a lot of code, study other people's code, ask more experienced colleagues to review your code. And remember, the moment you say to yourself, "that's good enough," is the moment your development stops.

Decide what entities should be in the program

You need to write code that’s understandable to other programmers. If 9 out of 10 programmers would make classes A, B, and C when designing a program, then you also need to make classes A, B, and C in your program. You need to write code that's understandable to others.

Excellent, working, fast, non-standard code is bad code.

You need to study other projects: it’s the best, fastest, and easiest way to absorb all the wisdom that has accumulated in the IT industry over decades.

And by the way, you already have an excellent, popular, well-documented project at your disposal — React. Start with that.

Analyze classes and class structures. Think about why some methods are static and others aren't. Why do methods have those specific parameters and not others? Why are there those specific methods, why are classes named like that and located in those specific packages?

Once you start understanding the answers to all these questions, you'll be able to write code that's understandable to others.

However, I want to warn you against analyzing code within methods of D3.js. The code for many methods has been rewritten for maximum performance — its readability is highly questionable.

Correctly break the program into logical parts

Any program is usually split into parts or modules. Each part is responsible for a certain aspect of the program.

Computers have a system unit, monitor, keyboard, and these are all separate, loosely related parts. Moreover, their interaction is standardized: USB, HDMI, etc. So if you spill coffee on the keyboard, you can just wash it under the tap, dry it, and keep using it.

A laptop, however, is an example of a monolithic architecture: logical parts do exist, but they are integrated much more tightly. In a Macbook Pro, to clean the keyboard, you have to disassemble half the laptop. And spilling coffee on a laptop means it’s time to order a new one. Just not coffee.

1.3 Creating Your Own Classes

You're just learning to program, so you need to start small — learning to create your own classes.

You've, of course, already created them, but you need to learn to understand what classes should be in a program, what they should be called, what methods they should have, and how they should interact with each other.

List of Entities

If you don't know where to start, start from the beginning.

At the very start of designing a program, you can just list out the entities (objects) that should be in the program on a piece of paper. Then program them with this principle: each entity is a separate class.

Example

Let's say you want to write a chess game. You'll need entities like a chessboard and 6 types of pieces. Pieces move differently, have different values — logically, these are separate classes. Generally, at the very beginning, the more classes, the better.

Finding a new programmer who writes ten classes instead of two is a rarity. Writing two or even one instead of ten, that’s what beginners love. So more classes, fellow programmers. And your code will become clearer to everyone except maybe you 😛

Chess

Let’s say we decided to write classes for chess: what would those classes look like?

Is the chessboard just an 8 by 8 array? It’s better to create a separate class for it that internally holds a reference to the array. That way, in the "chessboard" class, you can add many useful methods that, for example, check if a square is empty or occupied.

In general, in the beginning, you can always follow the principle: The program has different Entities, and an Entity has a type. That type is the class.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION