Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does strictly adhering to the Single Responsibility Principle violate encapsulation?

Tags:

oop

It seems that if I strictly adhere to the Single Responsibility principle, then I may have to add public getters in order to split functionalities that may change. To me, this seems to violate encapsulation by exposing the objects internal structure.

For example, assume I have a class that represents an uploaded file. In the past I have used methods like toHtml() in order to avoid getters and maintain encapsulation:

public class UploadedFile() {
  private String filename;
  private String uri;
  public String toHtml() {
    return <html string>;
 }

But I could see where one could argue that, based on SRP, you might want to include getters for filename and uri and generate the html elsewhere.

like image 384
Eric Avatar asked Nov 13 '22 21:11

Eric


1 Answers

In this situation, filename and uri would be properties of your UploadedFile() class that it would be illogical to keep hidden, so providing getters for those doesn't violate encapsulation at all, in my opinion.

The encapsulation violation would occur if you made filename and uri public fields and just accessed them directly.

like image 149
JAB Avatar answered Mar 09 '23 01:03

JAB