Categories
handson

HandsOn: Writing your own classes

It all starts with a plan

First step to take: plan your class. Ask yourself

  • what will it represent to find a decent name.
  • what attributes will it need to reflect it’s state.
  • what methods should the class have to provide functionality

What is you class about? Naming

In order to make your future class easy to use in code, name it by a noun (thing-word / concept) and use singular, because regardless of how many instance objects you will create, the class is one single blueprint for it.

By convention use an Uppercase letter at the first position, to later distinguish between e.g. calling an objects attribute or method, or a classes given static method.

Let’s return to an earlier example: A Person

person (drawing)
a Person

What attributes will your class need?

What could be possible be important attributes to record inside our class?

So far we recorded

  • first name
  • family name
  • date of birth

any other ideas?

A person with more attributes

in this picture, we see some more physical attributes e.g.

  • the weight
  • the waist size
  • foot size
  • shoulder length

and also some more abstract attributes, like

  • the number of an ID card (driving licence, e.g.)
  • gender (male, female, diverse, not known)

your use-case leads to the decision about attributes

Always keep your use-cases in mind. Select only those attributes that are important now or in future for your work. Don’t select attributes without a known use-case for your project.

  • If you’re project is for a public authority, you may want to select names, ID number, date of birth and similar attributes, but never care for a persons weight or feet size.
  • If you’re hired by an online shop that trades clothes, you may be interested in shoulders width, waist size and body height. Possibly in the gender of your customer, to provide suitable offers from your shop.
  • If you code for a company that sells fitness tracking hardware, maybe their customers want to track their weight loss or gain. So design that attribute into your class.

what should you class be able to “do”?

Methods will represent the functionality your class provides to you and other coders. Generally there are more or less categories of what methods do

  • manipulate or render data of the objects state attributes
  • add or cancel technical connections to other objects
    • observer pattern (“add me to your lists of listeners”)
  • reactions to events
    • execute this method when event x,y,z occurs (click, resize, data changed, timer events)
  • do calculations

As a convention (not a must, but best practice), methods usually use verbs (do-words) in infinitive form to describe their functionality. e. g. loadData, calculateVolume, addListener, removeItem. Think of the English sentence structure with subject predicate object, and get a feeling how your code will read like when writing statements of the shape object.method(parameter).

The English continuous verb forms read like passive, or more like questions to a reader.

Good verbalized method names help other coders to understand your class and re-use it. Finding a good method name also helps in the design process of classes, to decide if the granularity (size) of a method fits (does one method try to do too much things at once? it could be to heavy weight)

  • good example:
    • father.addChild(johanna);
    • stateObject.addUpdateListener(observingObject);
  • less good examples:
    • mother.ChildAdd(ahmed);
    • service.runningCommand(‘refresh process 20’);

The Syntax

The general syntax of a class looks like this:

// Klasse is the German word for class
class Klasse {
  attribut1 = 0; // Attribut is German for attributes
  // … more attributes 

  // This class constructor requires a parameter for 
  // passing the default value for attribut1
  constructor (attribut1Defaultvalue) {
    // initialization of state          
    this.attribut1 = attribut1Defaultvalue; 
    // ... more initialization 
  } 

  methode1(parameter1) { // Methode is German for method
   // todo: place code
  }

  methode2(parameter1, parameter2) {
    // todo: place code
  } 

  // ... more methods
}

Your Task!: #1

  • chose a use-case from above, to select some relevant attributes
  • write the code for your class in a single file named classname.js
  • load the file into the node.js terminal via .load command, to evaluate it
    • (be sure to start the node.js terminal from the directory where your file is located)
  • regardless of your chosen use-case add a dateOfBirth attribute
  • add a method for calculating the age of the person
// the age calculation will fail, 
// if dateOfBirth doesn't contain a Date instance
calculateCurrentAge() {
// get the current Date
  let currentDate = new Date();
  // split start date components
  let syear       = this.dateOfBirth.getYear();
  let smonth      = this.dateOfBirth.getMonth();
  let sday        = this.dateOfBirth.getDate();

  // split end date components
  let eyear       = currentDate.getYear();
  let emonth      = currentDate.getMonth();
  let eday        = currentDate.getDate();

  // normalize day of month to 30, if bigger
  if (sday === 31) sday = 30;
  if (eday === 31) eday = 30;
  // (don't change February 28 or February 29)
		
  // linearize the components to a harmonized value range
  let startLinear = (eday + emonth * 30 + eyear * 360);
  let endLinear   = (sday + smonth * 30 + syear * 360);
  // return the floored difference 
  return Math.floor((startLinear - endLinear) / 360);
}
  • create an instance object represents yourself
    • you’re allowed to lie about the birthday for reasons of data protection
  • use console.log() to test the calculateCurrentAge()-method

Now you know, how to plan own classes and write them down in code. Let’s move forward to some further concepts like setters and getters.

Leave a Reply

Your email address will not be published. Required fields are marked *