DEV Community

Discussion on: S.O.L.I.D: Single Responsibility Principle

Collapse
 
tylerwbrown profile image
Tyler Brown

Hey, nice post! The SRP is definitely a super important principle to keep in mind while coding.

However, to change the context here, let me change some of this code to use a newer Java 14 feature (the version of Java that's going to release later this month).

Instead of:

package app.singleResponsibility;

public class Employee {
  private String name;
  private int perHourRate;

  public Employee(String name) {
    this.name = name;
  }

  public String getName() {
      return name;
  }

  public void setPerHourRate(int rate) {
    this.perHourRate = rate;
  }

  public int getPerDayRate() {
    return perHourRate * 8;
  }
}

we can do:

package app.singleResponsibility;

public record Employee(String name, int perHourRate) {
  public int perDayRate() { 
    return perHourRate * 8; 
  }
}

Getters are handled automatically by records and they follow slightly different conventions. Setters don't exist, you'd instead "mutate" a record by making a new one.

The point here is that following the SRP depends on context. In older languages/versions, what might be considered breaking the SRP might not be anymore. As we move to higher level languages, the semantics improve and we can be more expressive about the code we write, which means a "single responsibility" encapsulates more than it used to.

I'm not disagreeing with your post here, just adding additional context to the discussion :)

And again, well done on the post!

Collapse
 
linuxnerd profile image
Abhishek Prakash

I am glad you liked the post! Thanks for the insight and definitely newer version of Java will help to reduce the verbosity. But, I am still confused how the context will impact the SRP. Can you explain with an example?