Rudy Deighton

  • Home
  • Inleiding
  • De Toekomst
  • Marketing Platform
    • Delta Media Strategie Modules
    • Online Marketing
    • Delta Social Media
    • Delta Media Service
    • Delta media Platform
    • Delta Marketing Platform
    • Online business marketing
    • Online Business
      • Worth for free now
      • Work from Home 2020
      • Gadgets
      • All about Windows
      • about Whatsapp
      • Whats the
      • About websites
      • New Ways
      • New Way of Watching
      • Virtual
      • Website
      • All about Video
      • How to Use
      • YouTube Info
      • All about Twitter
      • The Best of
      • About Apps
      • Google News
      • For Free
      • About This
      • Need More
      • Why should you
      • Iphone news
      • Interesting News
      • About Amazone
      • Some tips
      • About Netflix
      • All about Music
      • About Facebook
  • Luxury Platform
    • The Indulgence Business site
    • The Luxury Web site
    • The Ultimate Indulgence
    • The Indulgence Site
    • The Ultimate Luxury Information site
    • Online luxury
  • Projecten
    • Global Diamond Security
    • Aqualith Project
    • Delta Online Projects
    • Delta Media
    • Delta Media Projects
    • Crypto info
      • What is Cryptocurrency
      • Delta Media ICO systeem
      • Cryptocurrency Information
      • About miners
      • Best Bitcoin Bokers
      • Overview Cryptocurrency
      • BLOCKCHAIN WEB PLATFORM
      • Delta Media ICO Cryptocurrency
      • Bitcoin Ticker
      • ICO and Cryptocurrency modules
      • Cryptocurrency, Blockchain, Bitcoin modules
      • Delta Buy & Sale Token
      • Buy and sell digital currency module
      • ico – Crypto BlockChain Parallax module
      • Exchange Cryptocurrency module
  • Nieuws Platform
    • RegioTV Nieuws
    • Regionaal Nieuws Platform
    • Nieuws Regio’s Tiel
    • RegioTV Buren
    • RegioTV Neder-Betuwe
    • Regionaal Nieuws Tiel
    • Micro Locals Nieuws
    • Micro Locals project
    • Lokale CSM systeem
    • RegioTV nieuws
    • Politiek Nederland
    • Politiek Gelderland
    • Politiek Tiel
    • Regio Nieuwsberichten Tiel
    • Regionaal nieuws
    • Regionaal video nieuws
    • RegioTV Nieuws & info
    • Regio Nieuws
    • Online video nieuws
    • Online Nieuws
    • Nieuws online RegioTV
    • Regionale content video
  • Promotion
  • Delta Media
    • Delta Media
    • Adverteren grote fraude
    • Menu POS
    • Delta Global Security
    • Delta Evenementen
    • LinkedIn
    • Facebook
    • Facebook Group
    • Twitter
    • Terms & Policy
    • Contact
    • .
  • Ads prices
    • Online Blog promotion price
    • Online web sites prices
    • Global Promotion Platform
  • Home
  • Delta Media News
  • How to Keep Your Code Clean With Object Encapsulation | MakeUseOf
February 27, 2021

How to Keep Your Code Clean With Object Encapsulation | MakeUseOf

How to Keep Your Code Clean With Object Encapsulation | MakeUseOf

by rudy deighton / Saturday, 03 October 2020 / Published in Delta Media News

Encapsulation means keeping something isolated. If you put something in a capsule, the outside world can’t access it. Encapsulation is an important concept in object-oriented programming because it helps keep complex code manageable.

Why You Need Classes

Let’s say you have a petting zoo app with hundreds of thousands of lines of code. Now imagine that there’s a highly important object that is central to the whole application, called animal. What if every single part of the program that was an animal could access and change that object?

Unrestricted access would cause a lot of chaos. If a piglet uses animal to define its parameters, then animal will have piglet attributes. Now, let’s say a goat decides to use animal to define its parameters.

In JavaScript/TypeScript, that would look like this:

var animal = {name: "piglet", legs: 4, color: "pink", decoration: "snout"}
animal.name = "goat"
animal.decoration = "horns"

Next thing you know, you’ve got pink goats and piglets with horns. See the code in action at the TypeScript sandbox then click run to view console output.

If you’re learning to program and want inspiration besides creating a petting zoo, here are 10 more projects to inspire you.

Because your codebase is so huge, it could take hundreds of hours to find the code that’s giving your lambs llama necks and your ducklings wool. And once you do find the offending code, you will have to write even more spaghetti code to keep the objects from interfering with each other. There must be a better way.

The way to fix the overlap problem is by defining objects with classes. Any part of the code can create an object based on the class definition. Creating a unique object is called instantiation. It guarantees that every object created will have its own properties. And those objects won’t be able to interfere with each other accidentally.

Classes Aren’t Enough; Your Object Variables Need Encapsulation Too

So we’ve decided that every animal needs its own object. Let’s create a class that will define our animals.

class Animal {
name: string;
legs: number;
color: string;
decoration: string;
constructor(name: string, legs: number, color: string, decoration: string) {
this.name = name;
this.legs = legs;
this.color = color;
this.decoration = decoration;
}
}

Next, let’s create a couple of animal objects.

let babyDuck = new Animal("baby duck", 2, "yellow", "beak");
let bunny = new Animal("bunny", 4, "gray", "floppy ears");

Play with the code so far.

Now we can add all of the animals we want without any weird mutations. Or can we?

What would happen if one night, a tired programmer wrote some code to edit an animal from the creepy-crawly app, but they edited the bunny by mistake?

bunny.color = "black";
bunny.legs = 8;

Spider bunnies are not cool, man! That’s just as bad as when we didn’t encapsulate our code into objects. Let’s make sure that never happens again.

The first thing we need to do is to make our objects private. That means that nothing can edit our variables directly after creating them. Here’s the code showing that changing private variables creates an error.

Variables do need to be changeable, though. And that’s where getters and setters come in.

Getters and setters are functions that access and change variables in a controlled way. Setters can set limitations on the data that gets changed. And getters can alter the data that gets retrieved.

This is what our class looks like with get and set functions to control the leg count.

class Animal {
private _name: string;
private _legs: number;
private _color: string;
private _decoration: string;
constructor(name: string, legs: number, color: string, decoration: string) {
this._name = name;
this._legs = legs;
this._color = color;
this._decoration = decoration;
}
get legs() {
return this._legs;
}
set legs(legCount: number) {
if(legCount > 1 && legCount < 5) {
this._legs = legCount;
}
}
}

Learn Encapsulation and Avoid Global Variables

Here’s the final code. Recap what you’ve learned to ensure your understanding:

  • Add getters and setters for the rest of the variables.
  • Return the animal name as a span tag: <span>llama</span>
  • Change the decoration variable to allow for multiple decorations. Create an appropriate getter and setter to reflect that change.

If you want to keep your code running like a well-oiled machine, you absolutely need to use encapsulation. Avoid global variables at all costs. And if you do need to share variables between objects, you can view the TypeScript documentation on how to create class/static variables to learn how.

MakeUseOf – Feed

  • Tweet
Tagged under: Clean, Code, Encapsulation, Keep, MakeUseOf, Object

About rudy deighton

What you can read next

9 Cleanest & Safest Websites to Download Free Software for Windows
5 Easiest Meditation Tools for Beginners to Learn Mindfulness
Google Forms vs. SurveyMonkey: Which Survey Tool Is Right for You?

Rudy Deighton Corporate Blog

  • 6 Ways to Check Who Is Tracking You Online

    How much do you love online content? So much yo...
  • Apple Adds Repairability Scores to iPhones and MacBooks in France

    A lack of repairability is a criticism that has...
  • Canon Releases the EOS M50 Mark II Mirrorless Camera

    With the incredible reach that platforms like Y...
  • TerraMaster Launches the Upgraded D8 Thunderbolt 3

    World-leading storage hardware manufacturer Ter...
  • You Can Now Pre-Order the Ring Video Doorbell Pro 2

    Amazon-owned Ring has unveiled its latest video...
  • YouTube Launches Supervised Accounts for Parents of Tweens and Teens

    YouTube Kids is a little too limiting for older...
  • Microsoft Launches Windows 10 Cumulative Update Preview

    Microsoft has released the latest cumulative up...
  • How to Play Google Stadia on Your iPhone or iPad

    It’s been a long time coming, but Google ...
  • Is the DeviantArt Mobile App Worth Downloading?

    Years after deviantART launched in 2007, the ar...
  • TikTok Has Chosen 100 Users for Its Black Creatives Program

    During the second week of January, TikTok opene...
  • Microsoft, FireEye, CrowdStrike, and SolarWinds Speak at US Senate Hearing Into Massive Cyberattack

    Tuesday, 23 February, saw the first of a series...
  • What Happens If You Reject WhatsApp’s New Terms of Service?

    While WhatsApp has extended the deadline for it...
  • 5 Stress-Busting Apps to Rant to Strangers Online or Vent Into the Void

    Do you want to rant and rave about the frustrat...
  • Microsoft Launches Coalition to Combat Media Disinformation

    Microsoft is joining forces with other major te...
  • iOS 14.5 Will Crack Down on Zero-Click Attacks

    A zero-click attack is a terrifying kind of cyb...
  • The New Echo Show 10: Everything You Need to Know

    The Amazon Echo Show lineup took the features t...
  • Donald Trump Might Make His Own Social Media Platform

    After a flurry of people raided Capitol Hill la...
  • iPhone 12 Success Could Push Apple to Amazing $3 Trillion Valuation

    Apple’s valuation has had a rocket strapp...
  • 11 Ways to Easily Identify Manipulated Images

    Adobe Photoshop and other image editing tools b...
  • The 5 Best Apps Like Cash App

    Need to make a quick payment or send money to a...
  • TikTok and UFC Seal a Multi-Year Partnership

    Last week, TikTok was named the Global Sponsor ...
  • Report: Clubhouse Doubled Its Downloads in Two Weeks

    The scarcity principle says that the more rare ...
  • How to Mute Specific Words and Hashtags on Twitter

    Sometimes, Twitter can be an information overlo...
  • 6 Clubhouse Apps to Make the Audio Social Network Better and Solve Its Restrictions

    Finally, got an invitation to join Clubhouse? Y...
  • Report: Google Pixel Users Are Experiencing Camera Failure

    The Google Pixel devices are an impressive line...
  • How to Divide in Excel

    You don’t have to be a business analyst o...
  • How to Fix the "Task Manager Has Been Disabled By Your Administrator" Error in Windows 10

    Have you experienced a situation where you can&...
  • Nikon Announces Release Date for the Z6 II/Z7 II 1.10 Firmware Update

    Nikon ranked third behind Canon and Sony in the...
  • Microsoft Officially Announces Office 2021

    Microsoft has tried its hardest to convince peo...
  • Apple TV App Launches on Chromecast With Google TV

    The Apple TV App is now officially available on...
  • Hour One Debuts Its Digital Clone Technology

    Surely you’ve at least entertained the id...
  • Nintendo Announces Zelda-Themed Joy-Cons

    February’s Nintendo Direct has been and g...
  • Facebook Bans News in Australia Over Proposed Legislation

    Facebook is taking a stand against a proposed b...
  • New Amazon CEO Commits to Making Video Games, Unlike Google

    It is (kind of) official; Amazon will continue ...
  • Introducing FocusEx: A Digital Reading Aid for People with ADHD

    Have you ever found it difficult to stay focuse...
  • How to Enable Burst Photos on iPhone

    Burst mode has become a standard feature across...
  • 6 Reasons Why You Should Be Using pfsense Firewall

    When it comes to choosing firewall software, th...
  • How to Record, Edit, and Promote Your Own Podcast

    You listen to podcasts all the time—but h...
  • Microsoft Edge’s Collections Are Getting a Handy Update

    Microsoft has been working hard to make its Chr...
  • Regret Deleting an Instagram Post? Now You Can Restore It

    Instagram’s Recently Deleted feature allo...

DELTA MEDIA ONLINE MARKETING PLATFORM
An Arte di Riunire Investments GmbH Division

Office:
Delta Media

Arte di Riunire Investments GmbH

Address: Lood 207F

Postcode: 3803 Beatenberg (Swiss)

email: rudydeighton@hotmail.com

rudydeighton@deltamediagbe.com

 

 

Online Platform

Menu POS Systeem

  • GET SOCIAL
Rudy Deighton

© 2014 Delta Media - Arte di Riunire Investments GmbH Division - SWISS All Rights Reserved

TOP