Member-only story

Implementing Getters and Setters is contrary to the Single Responsibility Principle.

David Garcia
Stackademic
Published in
6 min readOct 21, 2024
Source: Google Search targeting YouTube - Object Oriented PHP #6 — Getters & Setters

Not a Medium Member? Read this article by clicking here.

Software Engineers need to consider the purpose of certain pieces of code. We all should aim to deliver maintainable code while it’s secure and does not perform side operations (we can do that with automated testing).

And, be honest, getters and setters are some of the most useless practices someone decides to implement (only because other people do it).

Please keep reading before yelling at me in the comments.

Let’s consider a sample code as follows:

class MyAwesomeClass
{
private string $property;

public function setProperty(string $value): void
{
$this->property = $value;
}

public function getProperty(): string
{
return $this->property;
}
}

$myAwesomeClass = new MyAwesomeClass();
$myAwesomeClass->setProperty($value);
var_dump($myAwesomeClass->getProperty());

The purpose of a setter is to “set a value to a property,” and the getter aims to “get a value from a property.” As simple as that. That’s why they are called getters and setters.

This means we can refactor all that logic with a much simpler one:

class MyAwesomeClass

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by David Garcia

Senior Software Engineer, Backend, NodeJS & Symfony developer, workaholic, passionate for new technologies and OSS contributor. https://linktr.ee/davidgarciacat

No responses yet

What are your thoughts?