codeasy.net
orSign Up

The Commander

The Commander

The next day, I was walking down the corridor when I heard Infinity's voice coming from the conference room. She sounded very stressed, which was far from her typical confident demeanor. The talk must be significant, I thought, and before I could stop myself, I began to eavesdrop.

"What do you mean, faster? I have all of my resources working on Rust; there's nothing left to add!" Infinity shouted.
"It's too slow. You haven't made any attacks during the last month," the male voice answered.
"My sister was kidnapped; she barely survived," Infinity shot back. "We couldn't just leave her there to be interrogated."
"You're putting your own interest higher than our mission. Your sister is just a programmer, we lose more and more every day," the voice said.

There was a pause. A long one. Even though I wasn't participating in the discussion, I could feel the tremendous tension in the air. Finally, Infinity got her voice back. "You are right, Commander. It won't happen again. Our mission is more important than my sister's life."

It was clear that this was what the commander was looking for Inifinity to say. But how does someone will themselves to say something so coarse and lifeless? It's easy to hear such phrases in movies, where the actors are playing roles, but to hear it in the context of an actual human life... Infinity giving her word that the next time there was a choice between completing a mission and saving her sister's life, she would choose the former. Scary. Is this why she was chosen as the leader of the resistance in Wonderland? Was it out of weakness or strength that she could decided to put the mission before her family? Who was the commander asking her to give up so much? Noname would probably know. With his deep access in the network, he probably had access to personnel files.

"Noname, who is in the conference room now?" I asked silently.
"Hi Teo, just one person, Infinity," Noname replied.
"She was talking to someone. Please check again," I said.
"In the modern world, Teo, there are ways to talk to people even if they're not in the same room! My records are spotty that far back, but I'm pretty sure it was possible in your time, 2018, as well. Maybe called a conference call? Such simple technology!"
"Noname, who was she talking to?" I began to miss the straight-to-the-point British personality Noname used to have.

"The channel was encrypted. I don't have any way to retrieve the credentials of whoever was talking to Infinity, sorry."
"That's fine, don't worry, friend," I replied.

Who was this Commander?

Encapsulation

In class the next day, we learned a new topic - encapsulation. Sintia was wearing jeans and a t-shirt, casual as usual.
"Have you ever heard the term 'encapsulation'? No? This is one of the fundamental concepts in object-oriented programming. Encapsulation has two goals:"

  1. Keeping the data, and methods for working with the data, in one unit (such as a class or struct in C#)
  2. Restricting direct access to some of the unit's components

"Sintia..." two students said over one another.
"I know, I know. Far too abstract. I'll explain by example. Take a look at this code snippet:"

class Car
{
    public void PrintPrice(decimal price)
    {
        Console.WriteLine($"Car costs {price}");
    }

    public void PrintDiscountPrice(decimal price, int discount)
    {
        Console.WriteLine($"Price with discount is {price - discount}");
    }
}

class CarSetup
{
    public static void Main()
    {
        var carPrice = decimal.Parse(Console.ReadLine());
        var carDiscount = int.Parse(Console.ReadLine());

        var car = new Car();
        car.PrintPrice(carPrice);
        car.PrintDiscountPrice(carPrice, carDiscount);
    }
}

"Does anything about this code jump out at you?" Sintia asked.
"Is anyone else using variables carPrice and carDiscount?" I asked.
"No, they are used only to call methods on an object of type Car."
"Then I don't see any sense in keeping carPrice and carDiscount outside of the class Car," I said.
"Good, Teo. So how would you rewrite this code snippet? Here, I'll show the result to the class," Sintia said, swiping on her tablet to show my work on the wall.

I rewrote the code as follows:

class Car
{
    public decimal Price;
    public int Discount;

    public void PrintPrice()
    {
        Console.WriteLine($"Car costs {Price}");
    }

    public void PrintDiscountPrice()
    {
        Console.WriteLine($"Price with discount is {Price - Discount}");
    }
}

class CarSetup
{
    public static void Main()
    {
        var carPrice = decimal.Parse(Console.ReadLine());
        var carDiscount = int.Parse(Console.ReadLine());

        var car = new Car
        {
            Price = carPrice,
            Discount = carDiscount
        };

        car.PrintPrice();
        car.PrintDiscountPrice();
    }
}

"Exactly how I would do it!" Sintia declared, sounding genuinely impressed.
"This code is a good representation of the first encapsulation concept: to keep data and methods that work with that data in one class. Class Car contains data fields Discount and Price, as well as the methods that work with those, PrintPrice and PrintDiscount," Sintia said.

The first encapsulation concept C#

"I can improve this code snipped even further!" said one of the students in the room.
"Go ahead!" Sintia projected the results of his work to the wall:

class Car
{
    public decimal Price { get; }
    public int Discount { get; }

    public Car(decimal price, int discount)
    {
        Price = price;
        Discount = discount;
    }

    public void PrintPrice()
    {
        Console.WriteLine($"Car costs {Price}");
    }

    public void PrintDiscountPrice()
    {
        Console.WriteLine($"Price with discount is {Price - Discount}");
    }
}

class SomeOtherClass
{
    public static void Main()
    {
        var carPrice = decimal.Parse(Console.ReadLine());
        var carDiscount = int.Parse(Console.ReadLine());

        var car = new Car(carPrice, carDiscount);

        car.PrintPrice();
        car.PrintDiscountPrice();
    }
}

"Okay, and can you explain why this is an improvement?" Sintia asked the student.
"Because this code corresponds to the second encapsulation concept: it restricts a direct access to all fields and sets the value through the constructor."

"Well done! In general, Public fields are usually not welcome in C#. Public fields expose the inner state of your class, allowing anyone to change it," Sintia summed up, adding, " The handout you picked up at the beginning of class lists more advantages of using encapsulation. Read it over, take a quick break, and we'll start coding in ten minutes."

  1. Controls values that are assigned to the inner state of your class. For example, if you have a public field Age, anyone can assign it an incorrect value, such as a negative number. In the case of properties, by encapsulating this field, you can add a validation step before storing a value for Age.
  2. Maintains consistency of the inner state of a class. Sometimes several objects are intending to change the same field in an object of your class. It may even happen simultaneously. To prevent collisions in simultaneous access to the same data and take control over the inner state of the class, you can make the field private or use a property. Thus, the changes in the inner state of your object could only be done by your object itself, not by others. Correct usage of encapsulation guarantees that no one can get direct access to the inner state of your class. It can only be accessed by using methods or properties.
  3. Makes it easier to change a publicly used class. Imagine that your class is used by dozens of other teams of coders in different projects, applications, countries... Then, changing the name of a single public method or field can lead to thousands of users with broken software. Sounds like a catastrophe, right? In contrast, changing the name of a private method or field is safe because no one can use it except your class itself.

"It feels like we're advancing into software architecture principles and best practices!" I told Sintia during the break.
"Exactly, Teo. To be a good programmer, you need to know more than just the syntax of a programming language. You have to have the right mindset."

"Okay everyone, take your seats," Sintia said. "Here are the tasks I want you to work through."

Change public fields in the class Elevator to properties with the same name and type. Leave getters and setters with default access modifiers.

Change public fields in the class User to properties with the same name and type. Leave getters and setters with default access modifiers. In the setter of the property Name, check whether the string is null or empty. If it is, do not assign that value.

Change public fields in the class Shop and GeoLocation to properties with the same names and types. Leave getters with default access modifiers and change access for setters to private. Add constructors to Shop and GeoLocation that take values for every property as parameters and assigns them.

Despite the fact that Wonderland has an idyllic name, crimes are still present here. We recently noticed that one particular coder is decreasing the value of every good they buy by 1 virus in order to save on every purchase.
Change the class Good to use properties with public getters and setters. The current code should still work, but decreasing of the price should have no effect. To achieve this, change the code in the Price's setter. You are not allowed to change any code outside of the Good class.

Practice C# at Codeasy

This site uses cookies. By continuing to browse this site you are agreeing to our use of cookies.

Got it!

0