Inappropriate coding practices - Ruby

Inappropriate coding practices - Ruby

Need

Enforcement of proper encapsulation in coding practices

Context

  • Usage of Ruby for building dynamic and object-oriented applications

Description

Non compliant code

        class User
  public
  attr_accessor :name, :email, :password
end
        
        

In the code snippet above, we have a class User with three fields: name, email, and password. The attr_accessor method is used to create getter and setter methods for these fields.

However, the public keyword before attr_accessor means that these fields can be accessed and modified from outside of the class. This violates the principle of encapsulation, which is a fundamental concept in object-oriented programming.

Encapsulation is meant to hide the internal states and values of an object and only allow them to be accessed and modified through methods. By having these fields as public, we risk exposing sensitive data (such as the password field) and allow them to be changed in ways that the class is not designed to handle. This can lead to data corruption and potential security risks.

Steps

  • Remove the 'public' keyword from the class definition.
  • Remove the 'attr_accessor' method and replace it with individual getter and setter methods for each field.
  • Make the fields private by using the 'private' keyword.
  • Define getter methods to access the field values.
  • Define setter methods to modify the field values.
  • Add any necessary validation or logic within the getter and setter methods.
  • Update any references to the fields within the class to use the getter and setter methods instead.

Compliant code

        class User
  private
  attr_writer :name, :email, :password

  public
  def name
    @name
  end

  def email
    @email
  end

  def password
    @password
  end

  def name=(value)
    @name = value
  end

  def email=(value)
    @email = value
  end

  def password=(value)
    @password = value
  end
end
        
        

The updated code respects the encapsulation principle by making the fields private and providing public getter and setter methods for accessing and modifying the field values.

1. The 'public' keyword has been removed from the class definition. 2. The 'attr_accessor' method has been replaced with individual getter and setter methods for each field. 3. The fields have been made private by using the 'private' keyword. 4. Getter methods have been defined to access the field values. These methods simply return the value of the corresponding field. 5. Setter methods have been defined to modify the field values. These methods take a value as an argument and assign it to the corresponding field. 6. Any necessary validation or logic can be added within the getter and setter methods. 7. Any references to the fields within the class should now use the getter and setter methods instead of directly accessing the fields.

References