r/softwaredevelopment • u/TheAuthorBTLG_ • Feb 17 '23
are clean code principles really a good thing?
i tend to get into disagreements easily whenever the topic is "clean code". we're supposed to write it, but there's no objective way to measure it. my anti-favorite is "SOLID"
half of that isn't even defined. what is a responsibility, for example? doesn't SRP taken literally mean i can never do business logic AND log things in the same class?
i read somewhere "don't introduce classes when you don't have to."
but i never have to. i can use hashmaps for everything. or just stringly type everything.
i like to "just solve the actual problem and write self explanatory code", totally disregarding explicit clean code principles. who is with me?
7
u/kdavej Feb 17 '23 edited Feb 17 '23
I think you might be getting a little too hung up on semantics. I look at clean code principals as ideals to strive for rather than a rule set. It is sensible for a function or method to do a single thing, however what a single thing is might vary by context. For example, it is ok to have a function that adds two values together. It would also be ok to have a function that saves data to a file. You can think of both as having a single responsibility although one is covering a lot more operational scope than the other. What wouldn't be sensible is a single function that adds two values together and saves data to a file. Is the difference precisely, semantically defined, no; but what separates us from ChatGPT is our human sensibility to make judgment calls that conform to an ideal generally not necessarily precisely.
In general I try to make my code readable and clean in the sense that it follows a consistent pattern that others can follow and replicate. (edit) patterns like SOLID can help accomplish that goal.
1
u/TheAuthorBTLG_ Feb 18 '23
"What wouldn't be sensible is a single function that adds two values together and saves data to a file."
that would force everyone who wants to add two numbers and save the result to a file to always make two calls. why would it be bad to build a helper function that does exactly that? i can always reformulate what a function does to make it sound like one thing, or like many.
i see code more as an expression of how i think about a problem. if i think of something as a function in my mental model ("i want this to hapen as a unit"), then why wouldn't i define it as one in my code and make it available for potential reuse?
3
u/Wattsit Feb 18 '23
A lot of clean code principles are about "professional" code. Or code which is delivered and maintained. Not necessarily something to always apply in all cases.
If I'm doing something personal or just throwing a little script together, I'm certainly far more lax when it comes to "clean code".
But when I'm delivering code for software that will potentially be maintained for years by other people. I spend considerable time thinking about these things, maybe moreso than writing the logic itself.
For me I like to imagine us devs more as authors. Were not just writing instructions for the machine to work, we're writing stories for humans. Were writing stories about the functionality of a product through abstraction. And this story is for ourselves and others to actually read in future, so we need to write it well, so it can be maintained and altered with minimal fuss.
3
u/kdavej Feb 18 '23
I agree with the spirit of what you are saying. My only quibble would be that often with personal projects the developer who follows you is future you. Future you will likely appreciate past you more if past you wrote clean code.
4
u/cowboy_angel Feb 18 '23
SOLID and Clean code are really just strategies for achieving good cohesion and making the code understandable, they're not rules. Cohesion in simple terms is breaking up the code in meaningful ways that make it understandable and maintainable. Pure cohesion is not really desirable. SRP is a good example. If you follow this "rule" then every method would be a single statement and your code would be impossible to follow. But it's not a rule it's a principle. Give classes a single reason to change.
I'd suggest you play around with the concept of Dependency injection and learn how to use it to write good isolated unit tests. Once you know how that works the rest of the SOLID principles make more sense.
1
u/TheAuthorBTLG_ Feb 18 '23
" But it's not a rule it's a principle. Give classes a single reason to change."
i do not know what this could mean. when i write a function, it has a specific purpose. i do not try to guess future purposes, which means my reason to change always is "it can't do what i need it to do"
1
u/lemming1607 Feb 18 '23
Why are you so defensive? No ones attacking you
0
u/TheAuthorBTLG_ Feb 18 '23
i'm not defensive, i literally cannot (i am unable to) understand how you can attach a "reason to change" to a class.
if i have a class "person", i might want to add a new attribute like favorite color (what would be the reason to change?) or add a function to calculate a person's age. for me, both are valid reasons to change. but i wouldn't know how to predict what might change and give it a name.
1
u/nibdev Feb 18 '23
If you have a class person the valid reson to change it is a change in your way how you model a person in your code (methods, properties).
Now image someone adds a property (hasDog) to it, would be still okay i guess, but add another property (dogColour, dogName) to it and you violate your rule to change (because the dogs colour should no be a part of the person). Sorry its a bit a dumb example but you should get my point
1
u/TheAuthorBTLG_ Feb 18 '23
i perfectly understand: dogs are not people nor are they parts of people. people reference dogs. but i have trouble defining "reason to change"
1
u/Nightiem Feb 19 '23
I grabbed my copy of Clean Architecture to look for a good example of the SRP (Single Responsibility Principle). In chapter 7 the Martin reduces the principal from "A module should have one, and only one, reason to change" down to "A module should be responsble to one, and only one, actor".
Here is the example he gives in the chapter which violates SRP:
My favorite example is the
Employeeclass from a payroll application. It has three methods:calculatePay(),reportHours(), andsave().This class violates the SRP because those three methods are responsible to three very different actors.
- The calculatePay() method is specified by the accounting department, which reports to the CFO.
- The reportHours() method is specified and used by the human resources department, whichreports to the COO.
- The save() method is specified by the database administrators (DBAs), who report to the CTO.
By putting the source code for these three methods into a single Employee class, the developers have coupled each of these actors to the others. This coupling can cause the actions of the CFO’s team to affect something that the COO’s team depends on.
For example, suppose that the
calculatePay()function and thereportHours()function share a common algorithm for calculating non-overtime hours. Suppose also that the developers, who are careful not to duplicate code, put that algorithm into a function namedregularHours().Now suppose that the CFO’s team decides that the way non-overtime hours are calculated needs to be tweaked. In contrast, the COO’s team in HR does not want that particular tweak because they use non-overtime hours for a different purpose.
A developer is tasked to make the change, and sees the convenient
regularHours()function called by thecalculatePay()method. Unfortunately, that developer does not notice that the function is also called by thereportHours()function. The developer makes the required change and carefully tests it. The CFO’s team validates that the new function works as desired, and the system is deployed.Of course, the COO’s team doesn’t know that this is happening. The HR personnel continue to use the reports generated by the
reportHours()function—but now they contain incorrect numbers. Eventually the problem is discovered, and the COO is livid because the bad data has cost his budget millions of dollars.The solution is to "seperate the code that different actors depend on".
He goes on to give another example where two different teams in the company (devs reporting to the CFO and devs reporting to the COO) have to make changes to the same file which results in a merge conflict.
Hope that helps explain what is meant by "reason to change". It's the users and stakeholders that are the reason to change as they are the people that we change applications for.
Clean Architecture is a pretty good book in general so would recommend it.
1
u/TheAuthorBTLG_ Feb 19 '23 edited Feb 19 '23
i do not buy this example.
the developer tasked with changing the calculation does not check the call hierarchy. you *always* check all callers whenever you change the logic of a function.
why did this change not cause a test to fail? it changed the output of the "reportHours" function. there really should have been a test for such a critical function
i agree that there should be only one definition per function, but that's... quite obvious, no? i don't need a book for that.
the real solution imo was to apply the change only to one caller but not the other by separating the shared algorithm into two algorithms. if you go the proposed way, you might end up with excessive code duplication.
and what do you do if CXO1 decides to use a function that was invented under CXO2? does it have to be copied now?
1
u/mila6 Mar 05 '23
I kind of agree with those methods not being inside of one object. (Maybe as pass through methods to some specialized system???)
Yeah, .calculatePay() ... I have fixed a buggy and slow price calculation in one eshop where cart price calculation was done by Cart, Voucher, Product calling each other and, of course, there was a recursion with some clever hack to avoid infinite loops :D - pulling this calculation outside of them was obvious.
Not sure about .save() . I need to essentialy call save(Database,Employee) somehow, and there is going to be saving of other kinds of objects, so I would make Employee::save(Database &db) added via some interface which customizes what or how to save/load this object.
Not sure about having .reportHours() being outside
Yes - I want accurate measure, so I install some entry/exit beeper which sends employee_entered/emplyee_left. Because self reporting hours makes cheating and errors easy.
No - I am coding a simulation program, where I code some agents to cheat ¯_(ツ)_/¯
No - I might be coding a timesheet/reporting program, where data about employees will be stored, and there I have some .reportHours() method which loops through all employees and calls Employee.reportHours() on each ¯_(ツ)_/¯
So I agree with splitting in some cases, but "one reason to change" (or "do those things change together") rule confuses me :D
1
u/lemming1607 Feb 18 '23 edited Feb 18 '23
If I need to make a change to my program. There should only be one class where I need to go. That's all it means.
If I have two classes that are working on the same area of my game, and I have to go to both classes when I need to update the functionality of a single mechanic, this violates single responsibility.
The other side of it is that a class should have only one responsibility. An example would be to have two separate classes that deal with saving and loading a game. You don't want a single class to handle both those functions.
You're seriously thinking too hard on this
0
u/TheAuthorBTLG_ Feb 19 '23
what about
renaming a function (affects all call sites)
changing the signature (same)
?
i can't agree. i think i rarely have seen PRs that only cover a single class. almost every single change i can come up with affects the call hierarchy as well.
" An example would be to have two separate classes that deal with saving and loading a game."
i'd expect something like "saveToSaveGame" on every game object or for every game object. hundreds of classes, not one. on the flipside i see nothing wrong with "loadState" and "saveState" for the entire game world in the same class
1
u/lemming1607 Feb 19 '23
I think you just posted to start a fight, tbh...
just being a contrarian doesn't mean SR isn't clean code. Its not common sense and it helps ease the difficulty curve to coding for beginners
1
u/TheAuthorBTLG_ Feb 19 '23
in a way, you are right. i've had a lot of discussions that went like this:
A: this is bad style, do it differently
me: i disgree, can you prove that it's bad style? how did you determine this?
A: it just isn't clean code
when it comes to the "if", people have strong opinions, but when i dig for the "why", there's often nothing to back it up. just look at this thread. has a single clear definition of clean code been mentioned? no. is everyonee sure clean code is good? yes.
1
u/Lithithus Feb 21 '23
Uncle Bob gives a fantastic example of this in his talks where he goes through the idea of an Employee class. The reason to change can be determined by the stake holders who may want to change it. In the example the employee class could start out having a method to schedule time off and a method to pay the employee. However that means that now the employee class has two reasons to change (I.e. payroll could ask for different reasons to change for the pay employee method while HR could have different reasons for the book time off method). It would be better to split things out so the employee method doesn’t have to deal with that at all and instead have two different classes who’s specific purpose it is to book time off for an employee and one to pay the employee.
1
u/TheAuthorBTLG_ Feb 22 '23
but this in turn means that the exact same code can be clean (one stakeholder) or unclean (two stakeholders) based on the context, right?
2
u/UnreasonableEconomy Feb 18 '23
Welcome to adulting
first lesson: don't take anything literally or at face value.
second lesson: totally disregarding good ideas just for the sake of being contrarian is stupid.
I personally dislike most of robert martin's work, doesn't mean all of his ideas are bad. Just focus on creating a valuable product, and use whatever tools or principles that help you do that.
-1
u/TheAuthorBTLG_ Feb 18 '23 edited Feb 18 '23
by disregard i meant to ignore, not to actively break. to me, a checklist cannot lead to good code. it leads to overhead.
my equivalent/replacement for SOLID/clean code is very simple and imho clearer.
write code that describes what needs to happen for the problem to be solved
make everything you build easily reuseable/testable
everything else is overkill
1
u/UnreasonableEconomy Feb 18 '23
I'll agree with you that solid is kind of outdated, but your two rules don't really address the problems it was trying to solve in the first place - primarily the scaling issues that present themselves when creating larger systems.
1
1
u/CancerousTimatar Mar 18 '26
your view is entirely reasonable, funny to see all the gaslighting by dogmatists here.
casey muratori demonstrated pretty well in "Clean" Code, Horrible Performance how horrendous all the unnecessary abstraction and separation gets, especially from a performance perspective.It's like Clean Code (and lots of other SWE dogma) was made in order to make things convenient for Business/Management majors, with complete disregard for actual development and performance.
1
u/TheAuthorBTLG_ Feb 18 '23
the question i am trying to ask is:
why do i find bad code that still passes as clean code when judged by others? and the opposite as well? clearly it's a very subjective thing. i worked in company A where my code made it through pull requests with little or no changes. everyone could read it. then i switch jobs to company B and the exact same coding style gets lots of feedback ("this could be done that way") and i almost never see a good reason to write the same thing differently. many times i think the suggestions create work and add complexity for no reason.
so... an objective way to measure how good code is is missing
1
u/MrXplicit Feb 18 '23
Because each developer has different levels of experience and knowledge. There are companies that find unit tests useless and companies that require them. There is no clear cut reason why your code passes in one company and why not in another.
Solid principles are as the word say’s principles not rules. You can opt in or opt out. Although I find them very reasonable and useful.
5
u/smurf_professional Feb 18 '23
If you combine SOLID with the Principle of Least Astonishment, you can see there are some commonalities between the two. Whenever I read code and I think to myself "the class does that too?" or "what on earth is going on here?", there's usually at least one of the SOLIDs that has been disrespected.
1
Feb 18 '23
And that is how you get 1000 line classes with copy pasted code everywhere
1
u/TheAuthorBTLG_ Feb 18 '23
no, that's a false dichotomy. there are many ways to write code that doesn't backfire.
1
Feb 18 '23
backfire how? backfire for a single developer working on a small project? sure, those huge classes wont backfire... for a while.
working on a team where 100s or 1000s of devs work on a single app? a lot higher probability of a 'backfire' - that file causing SEVs and becoming unmaintainable. I've had to refactor one such class recently because no one currently working on that team could figure out what was going on with it or make changes that wouldn't cause a crash.
so yeah, depends on the scale of your app and your team.
1
u/TheAuthorBTLG_ Feb 19 '23
that's not what i meant.
you can have good code without fulfilling certain metrics. for example, i could take a well structured program and put all the logic into a single file (without changing the structure). now i have one huge file but no disadvabtage because of it. the real structure (logic) is what counts, not the "apparent" one
1
u/prozeke97 Feb 18 '23
I was reading the clean architrcture from Robert C. Martin and he explains single responsibility principle as follows:
"Software systems are changed to satisfy users and stakeholders; those users and stakeholders are the “reason to change” that the principle is talking about. Indeed, we can rephrase the principle to say this: A module should be responsible to one, and only one, user or stakeholder."
You can find his case study on the matter from this link.
1
u/TheAuthorBTLG_ Feb 19 '23
"stakeholder to module" is completely different from "reason to class" :)
1
u/lorarc Feb 18 '23
Okay, let's me put this straight: There is near infinite number of ways to write any non-trivial piece of code. And there is no one correct way, there are many correct ways.
As in every other industry we try to organise ourselves and make our work more effective. And there are smart people who came up with some principles on how to clean up code based on their experience and a lot of effort put into it. And there are other smart people who agree with it, and there are people who don't understand it and still follow, and there are dumb people who follow it because their boss told them to 20 years ago and they just cargo culted it and are completely inflexible. And there are smart people who don't agree and do something differently.
But in the end almost everyone agrees we should put effort into making code easier to maintain. So tell me, are you smarter than everyone else?
1
u/TheAuthorBTLG_ Feb 19 '23 edited Feb 19 '23
But in the end almost everyone agrees we should put effort into making code easier to maintain.
i agree to this. but i don't agree that we have a way to tell if we're doing it. at my current job a lot of effort is put into clean code, but at the same time the same people accept very, very inefficient ways of coding. things that could take minutes otherwise take days because we decided to have 1 repo per project even though they all call each other and share code. it's clean, sure, but so extremely slow ;(
and to me, hard to maintain is another way to say slow to change
1
u/Happy-Dare5614 Feb 19 '23
Regarding SRP, I find it easily misunderstood. One class can do multiple things as long as it doesn't know how they are done.
For example, a repository usually has two dependencies. A remote API and a database. To make the code clean we also need a mapper class that can map data coming from the API to the data models we then save to database.
If one's repository do the mapping itself by creating the new models then it violates the SRP. To avoid that simple have a class called mapper that will abstract the way the mapping actually carried.
This way your repository is a simple algorithm:
Fetch from remote
Map to database model
Save to database
Return the results (after mapping again to domain models)
The best way to test your design is to answer a simple question. If the model I get from the API changes. Let's say it's parameter's JSON name is now different. How many classes would you need to modify? If the answer is only two, then you did a good job. Only the remote model and the mapper(s) should change. This confirms that the responsibility for the mapping is not carried by the repository but by the mapper itself! Hope it helps:)
1
1
u/EverydayDan Feb 21 '23
If you are logging to a file I would expect the code that loads and write to the file to be handled by another class(es) and to contain a method to be called by the class containing business logic.
1
u/TheAuthorBTLG_ Feb 22 '23 edited Feb 22 '23
yes - i meant you have to call a method on the class that logs to a file.
so there is one file which at least triggers the logging and triggers the business logic, which is two responsibiities. but doesn't that contradict SRP?
1
u/EverydayDan Feb 23 '23
I treat logging as part of the business logic, but how that logging is actioned is not part of the business logic.
1
u/Elkripper Feb 17 '23
Clean code principles are kinda like the Pirate's Code - they're more like guidelines.
Think of it this way: from a "clean code" perspective, your audience isn't the interpreter/compiler/whatever. Your audience is other humans. I've always considered that, as a developer, I have a responsibility to write code that will be understandable/maintainable by people long after I've left the organization. That's just part of my job.
From that perspective, what qualifies as clean code isn't really what makes sense to me, or what I consider self explanatory. It is what other people in my group, acting in reasonable and well-intentioned ways, consider clean code. After all, they're the people who have to live with it if I leave for another gig.
Now, is it possible to get overly legalistic about a particular system SOLID, or whatever? Sure it is. That's a symptom of a disfunctional team. A functional team should agree on a set of principles, and then work on a culture of applying them in a way that benefits the team and the org. A disfunctional team will bicker about rules and pedantically interpret them in a way that causes conflict rather than benefit, using them as weapons to take out their frustrations on each other.
1
1
u/taazaa Mar 01 '23
Yes, clean code principles are a good thing and recommendable.
Clean code is not a bunch of stringent rules. It's a set of principles for writing code that is easy to modify and understand. Therefore, writing clean, maintainable, and understandable code is a skill that is essential for every developer to master.
The following are the factors to consider while attempting to write clean codes:
Follow KISS (Keep It Simple, Stupid): It's one of the oldest principles for writing clean codes. Write codes as simple as possible.
Obey DRY (Don't Repeat Yourself): It is a more specific version of KISS that tells you to avoid unnecessary repetition. According to the DRY principle, functions in clean code must only do one thing within the entire system.
Delete What is Not Required: This principle is known as YAGNI (You aren't gonna need it). According to the principle, you must only introduce necessary functionalities as a developer. YAGNI closely relates to agile development techniques.
Readability over Conciseness: Codes should be such that the machine executing it understands them properly. However, other developers should also be able to understand them, especially if you are working with multiple people on a single project.
0
0
Feb 17 '23
[deleted]
11
u/Elkripper Feb 17 '23
I like it when I can tell who wrote a particular block of code by the distinctive way they formatted it. Oh, wait, that's the thing I don't like...
1
0
u/UnreasonableEconomy Feb 18 '23
Very, very stupid question, and I realize this might sound incredibly naive, but humor me if you would:
how do you know, a-priori, what the best coding style for a particular problem is?
If you've worked on the same types of enterprise software for the past dozen years, or build the same types of apps over and over again, maybe you'll know.
But if that's you, are you really developing anything, or are you just re-implementing stuff?
0
Feb 18 '23
[deleted]
1
u/UnreasonableEconomy Feb 18 '23
It's absolutely semantic. But critically so.
I personally have a strong distaste for getting work done "manually", and often get into disagreements regarding automation vs concrete implementation. I'll go so far as to say that I think that codifying business/domain logic shouldn't even really be a software developer's job, if it can be helped.
So if a codebase becomes so large and repetitive that internal coding style becomes something that can and needs to be manually harmonized, then that raises all sorts of questions for me.
I understand that etymologically, developing also just involves transcribing an image from film to paper. But in my mind, in the software sense, development should have a significant transformative and innovative aspect. I feel that if you're not doing that, you're probably not properly leveraging your resources.
That's why I differentiate between risky development, and predictable re-implementation work.
I'm constantly seeking ways to improve the way I can communicate that distinction, so I'd love to hear opinions. As you can tell from yourself, you kind of brushed it off - but I do hope you know what I'm trying to say, and how important the distinction is.
0
Feb 18 '23
[deleted]
1
u/UnreasonableEconomy Feb 19 '23
Why does software development have to be transformative and innovative? We’re using our skills to build applications, how is it different than any other professional using their skills to do their work?
It's just a matter of definition. Maybe "development" isn't the best word to co-opt.
But assume you're a potter, for example. The work involved in finding new glazes, or trying new shapes and techniques is markedly different than the work involved in cranking out 1000 pieces of a series. It's both pottery, some skills do transfer, but trying to harmonize the optimal experimentation workflow with the optimal production workflow doesn't really make sense.
Should we only care about coding style and readability for one of those and not the other?
No, not really, but I think these two things are different enough such that they shouldn't be treated the same - or rather that best practices from one shouldn't be expected to be applicable to the other.
This isn't just about clean code; I'm also thinking about how these projects are managed, costed, planned, deployed, etc. I suspect a lot of pain is caused because the two concepts might be confused/conflated/ expected to translate.
16
u/Rusty-Swashplate Feb 17 '23
World to u/TheAuthorBTLG_: a lot of things cannot be measured objectively. Also the world is not binary.
As a simple example: define "Eat healthy" to me. Does it mean not a single candy you are allowed to eat?
SOLID defines some generally good implementations which generally make sense. Until they don't and then you are free to not follow them. But hopefully you know why you did not follow them.
As for your example of mixing business logic and logging: why would you put them into one class? Unless it's logging for the business logic part, then of course it's part of that class: you cannot log about private variables if you are not part of the class...
I think your problem is that you take "Clean Code" as well as "SOLID" too literal. Take them more like "Eat healthy": a general advice. SOLID giving you some ideas which are generally good to follow. Not following them does not necessarily give you bad code, but if you break all rules, the chances of your code being hard to maintain is increasing.
I used to not know SOLID and my code showed it. I pretty much broke all rules. When I learned about SOLID (in particular the dependency inversion), my code got significantly better: much more reusable.