How do you justify more code being written by following clean code practices?Is there such a thing as having too many private functions/methods?How clean should new code be?How do I prevent unknowningly duplicating code?OO - are large classes acceptable?How do I introduce clean code?MVC Controller - keeping methods smallClean Code comments vs class documentationHow to avoid …Helper or …Manager classesAre clean coding rules less relevant for large open source projects?My boss asks me to stop writing small functions and do everything in the same loopClean Code and the Principle of Least Astonishment
Why is indicated airspeed rather than ground speed used during the takeoff roll?
Why are there no stars visible in cislunar space?
What kind of footwear is suitable for walking in micro gravity environment?
Friend wants my recommendation but I don't want to
Norwegian Refugee travel document
Should I be concerned about student access to a test bank?
PTIJ: Which Dr. Seuss books should one obtain?
Was World War I a war of liberals against authoritarians?
When did hardware antialiasing start being available?
Justification failure in beamer enumerate list
Why is there so much iron?
Determine voltage drop over 10G resistors with cheap multimeter
What is the tangent at a sharp point on a curve?
Isn't the word "experience" wrongly used in this context?
What is it called when someone votes for an option that's not their first choice?
Hot air balloons as primitive bombers
How to balance a monster modification (zombie)?
Gauss brackets with double vertical lines
Have any astronauts/cosmonauts died in space?
Is xar preinstalled on macOS?
Knife as defense against stray dogs
How can a new country break out from a developed country without war?
Homology of the fiber
Weird lines in Microsoft Word
How do you justify more code being written by following clean code practices?
Is there such a thing as having too many private functions/methods?How clean should new code be?How do I prevent unknowningly duplicating code?OO - are large classes acceptable?How do I introduce clean code?MVC Controller - keeping methods smallClean Code comments vs class documentationHow to avoid …Helper or …Manager classesAre clean coding rules less relevant for large open source projects?My boss asks me to stop writing small functions and do everything in the same loopClean Code and the Principle of Least Astonishment
I've been following some of the practices recommended in Robert Martin's "Clean Code" book, especially the ones that apply to the type of software I work with and the ones that make sense to me (I don't follow it as dogma).
One side effect I've noticed, however, is that the "clean" code I write, is more code than if I didn't follow some practices. The specific practices that lead to this are:
- Encapsulating conditionals
So instead of
if(contact.email != null && contact.emails.contains('@')
I could write a small method like this
private Boolean isEmailValid(String email)...
- Replacing an inline comment with another private method, so that the method name describes itself rather than having an inline comment on top of it
- A class should only have one reason to change
And a few others. The point being, that what could be a method of 30 lines, ends up being a class, because of the tiny methods that replace comments and encapsulate conditionals, etc. When you realize you have so many methods, then it "makes sense" to put all the functionality into one class, when really it should've been a method.
I'm aware that any practice taken to the extreme can be harmful.
The concrete question I'm looking an answer for is:
Is this an acceptable byproduct of writing clean code? If so, what are some arguments I can use to justify the fact that more LOC have been written?
EDIT
To add some more detail, the organization is not concerned specifically about more LOC, but more LOC can result in very big classes (that again, could be replaced with a long method without a bunch of use-once helper functions for readability sake).
When you see a class that is big enough, it gives the impression that the class is busy enough, and that its responsibility has been concluded. You could, therefore, end up creating more classes to achieve other pieces of functionality. The result is then a lot of classes, all doing "one thing" with the aid of many small helper methods.
THIS is the specific concern...those classes could be a single class that still achieves "one thing", without the aid of many small methods. It could be a single class with maybe 3 or 4 methods and some comments.
object-oriented-design clean-code
New contributor
|
show 13 more comments
I've been following some of the practices recommended in Robert Martin's "Clean Code" book, especially the ones that apply to the type of software I work with and the ones that make sense to me (I don't follow it as dogma).
One side effect I've noticed, however, is that the "clean" code I write, is more code than if I didn't follow some practices. The specific practices that lead to this are:
- Encapsulating conditionals
So instead of
if(contact.email != null && contact.emails.contains('@')
I could write a small method like this
private Boolean isEmailValid(String email)...
- Replacing an inline comment with another private method, so that the method name describes itself rather than having an inline comment on top of it
- A class should only have one reason to change
And a few others. The point being, that what could be a method of 30 lines, ends up being a class, because of the tiny methods that replace comments and encapsulate conditionals, etc. When you realize you have so many methods, then it "makes sense" to put all the functionality into one class, when really it should've been a method.
I'm aware that any practice taken to the extreme can be harmful.
The concrete question I'm looking an answer for is:
Is this an acceptable byproduct of writing clean code? If so, what are some arguments I can use to justify the fact that more LOC have been written?
EDIT
To add some more detail, the organization is not concerned specifically about more LOC, but more LOC can result in very big classes (that again, could be replaced with a long method without a bunch of use-once helper functions for readability sake).
When you see a class that is big enough, it gives the impression that the class is busy enough, and that its responsibility has been concluded. You could, therefore, end up creating more classes to achieve other pieces of functionality. The result is then a lot of classes, all doing "one thing" with the aid of many small helper methods.
THIS is the specific concern...those classes could be a single class that still achieves "one thing", without the aid of many small methods. It could be a single class with maybe 3 or 4 methods and some comments.
object-oriented-design clean-code
New contributor
53
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
2
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
7
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
3
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
5
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago
|
show 13 more comments
I've been following some of the practices recommended in Robert Martin's "Clean Code" book, especially the ones that apply to the type of software I work with and the ones that make sense to me (I don't follow it as dogma).
One side effect I've noticed, however, is that the "clean" code I write, is more code than if I didn't follow some practices. The specific practices that lead to this are:
- Encapsulating conditionals
So instead of
if(contact.email != null && contact.emails.contains('@')
I could write a small method like this
private Boolean isEmailValid(String email)...
- Replacing an inline comment with another private method, so that the method name describes itself rather than having an inline comment on top of it
- A class should only have one reason to change
And a few others. The point being, that what could be a method of 30 lines, ends up being a class, because of the tiny methods that replace comments and encapsulate conditionals, etc. When you realize you have so many methods, then it "makes sense" to put all the functionality into one class, when really it should've been a method.
I'm aware that any practice taken to the extreme can be harmful.
The concrete question I'm looking an answer for is:
Is this an acceptable byproduct of writing clean code? If so, what are some arguments I can use to justify the fact that more LOC have been written?
EDIT
To add some more detail, the organization is not concerned specifically about more LOC, but more LOC can result in very big classes (that again, could be replaced with a long method without a bunch of use-once helper functions for readability sake).
When you see a class that is big enough, it gives the impression that the class is busy enough, and that its responsibility has been concluded. You could, therefore, end up creating more classes to achieve other pieces of functionality. The result is then a lot of classes, all doing "one thing" with the aid of many small helper methods.
THIS is the specific concern...those classes could be a single class that still achieves "one thing", without the aid of many small methods. It could be a single class with maybe 3 or 4 methods and some comments.
object-oriented-design clean-code
New contributor
I've been following some of the practices recommended in Robert Martin's "Clean Code" book, especially the ones that apply to the type of software I work with and the ones that make sense to me (I don't follow it as dogma).
One side effect I've noticed, however, is that the "clean" code I write, is more code than if I didn't follow some practices. The specific practices that lead to this are:
- Encapsulating conditionals
So instead of
if(contact.email != null && contact.emails.contains('@')
I could write a small method like this
private Boolean isEmailValid(String email)...
- Replacing an inline comment with another private method, so that the method name describes itself rather than having an inline comment on top of it
- A class should only have one reason to change
And a few others. The point being, that what could be a method of 30 lines, ends up being a class, because of the tiny methods that replace comments and encapsulate conditionals, etc. When you realize you have so many methods, then it "makes sense" to put all the functionality into one class, when really it should've been a method.
I'm aware that any practice taken to the extreme can be harmful.
The concrete question I'm looking an answer for is:
Is this an acceptable byproduct of writing clean code? If so, what are some arguments I can use to justify the fact that more LOC have been written?
EDIT
To add some more detail, the organization is not concerned specifically about more LOC, but more LOC can result in very big classes (that again, could be replaced with a long method without a bunch of use-once helper functions for readability sake).
When you see a class that is big enough, it gives the impression that the class is busy enough, and that its responsibility has been concluded. You could, therefore, end up creating more classes to achieve other pieces of functionality. The result is then a lot of classes, all doing "one thing" with the aid of many small helper methods.
THIS is the specific concern...those classes could be a single class that still achieves "one thing", without the aid of many small methods. It could be a single class with maybe 3 or 4 methods and some comments.
object-oriented-design clean-code
object-oriented-design clean-code
New contributor
New contributor
edited 11 hours ago
CRDev
New contributor
asked 15 hours ago
CRDevCRDev
31827
31827
New contributor
New contributor
53
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
2
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
7
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
3
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
5
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago
|
show 13 more comments
53
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
2
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
7
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
3
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
5
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago
53
53
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
2
2
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
7
7
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
3
3
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
5
5
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago
|
show 13 more comments
10 Answers
10
active
oldest
votes
... we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain
These folk have correctly identified something: they want the code to be easier to maintain. Where they've gone wrong though is assuming that the less code there is, the easier it is to maintain.
For code to be easy to maintain, then it needs to be easy to change. By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one. Tests are code, so writing those tests is going to swell your code base. And that is a good thing.
Secondly, in order to work out what needs changing, you code needs to be both easy to read and easy to reason about. Very terse code, shrunk in size just to keep the line count down is very unlikely to be easy to read. There's obviously a compromise to be struck as longer code will take longer to read. But if it's quicker to understand, then it's worth it. If it doesn't offer that benefit, then that verbosity stops being a benefit. But if longer code improves readability then again this is a good thing.
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
|
show 11 more comments
Yes, it's an acceptable byproduct, and the justification is that it is now structured such that you don't have to read most of the code most of the time. Instead of reading a 30-line function every single time you are making a change, you are reading a 5-line function to get the overall flow, and maybe a couple of the helper functions if your change touches that area. If your new "extra" class is called EmailValidator
and you know your problem isn't with email validation, you can skip reading it altogether.
It's also easier to reuse smaller pieces, which tends to reduce your line count for your overall program. An EmailValidator
can be used all over the place. Some lines of code that do email validation but are scrunched together with database access code can't be reused.
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
add a comment |
Bill Gates was famously attributed as saying, "Measuring programming progress by lines of code is like measuring aircraft building progress by weight."
I humbly agree with this sentiment. This is to not say that a program should strive for more or less lines of code, but that this isn't ultimately what counts to create a functioning and working program. It helps to remember that ultimately the reason behind adding extra lines of code is that it is theoretically more readable that way.
Disagreements can be had on whether a specific change is more or less readable, but I don't think you'd be wrong to make a change to your program because you think by doing so you're making it more readable. For instance making an isEmailValid
could be thought to be superfluous and unnecessary, especially if it is being called exactly once by the class which defines it. However I would much rather see an isEmailValid
in a condition than a string of ANDed conditions whereby I must determine what each individual condition checks and why it is being checked.
Where you get into trouble is when you create a isEmailValid
method which has side effects or checks things other than the e-mail, because this is worse than simply writing it all out. It is worse because it is misleading and I may miss a bug because of it.
Though clearly you're not doing that in this case, so I would encourage you to continue as you're doing. You should always ask yourself if by making the change, it is easier to read, and if that is your case, then do it!
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
add a comment |
so some developers/managers see value in writing less code to get things done so that we have less code to maintain
This is a matter of losing sight on the actual goal.
What matters is lowering hours spent on development. That is measured in time (or equivalent effort), not in lines of code.
This is like saying that car manufacturers should build their cars with less screws, because it takes a non-zero amount of time to put each screw in. While that is pedantically correct, a car's market value is not defined by how many screws it does or doesn't have. Above all else, a car needs to be performant, safe, and easy to maintain.
The rest of the answer are examples of how clean code can lead to time gains.
Logging
Take an application (A) which has no logging. Now create application B, which is the same application A but with logging. B will always have more lines of code, and thus you need to write more code.
But a lot of time will sink into investigating issues and bugs, and figuring out what went wrong.
For application A, developers will be stuck reading the code, and having to continually reproduce the problem and step through the code to find the source of the issue. This means that the developer has to test from the beginning of the execution to the end, in every used layer, and needs to observe every used piece of logic.
Maybe he is lucky to find it immediately, but maybe the answer is going to be in the last place he thinks of looking.
For application B, assuming perfect logging, a developer observes the logs, can immediately identify the faulty component, and now knows where to look.
This can be a matter of minutes, hours or days saved; depending on the size and complexity of the codebase.
Regressions
Take application A, which is not DRY-friendly at all.
Take application B, which is DRY, but ended up needing more lines because of the additional abstractions.
A change request is filed, which requires a change to the logic.
For application B, the developer changes the (unique, shared) logic according to the change request.
For application A, the developer has to change all instances of this logic where he remembers it being used.
- If he manages to remember all instances, he'll still have to implement the same change several times.
- If he does not manage to remember all instances, you're now dealing with an inconsistent codebase that contradicts itself. If the developer forgot a rarely used piece of code, this bug may not become apparent to the end users until well into the future. At that time, are the end users going to identify what the source of the issue is? Even if so, the developer may not remember what the change entailed, and will have to figure out how to change this forgotten piece of logic. Maybe the developer doesn't even work at the company by then, and then someone else now has to figure it all out from scratch.
This can lead to enormous time wastage. Not just in development, but in hunting and finding the bug. The application can start behaving erratically in a way that developers cannot easily comprehend. And that will lead to lengthy debugging sessions.
Developer interchangeability
Developer A created application A. The code is not clean nor readable, but it works like a charm and has been running in production. Unsurprisingly, there is no documentation either.
Developer A is absent for a month due to holidays. An emergency change request is filed. It can't wait another three weeks for Dev A to return.
Developer B has to execute this change. He now needs to read the entire codebase, understand how everything works, why it works, and what it tries to accomplish. This takes ages, but let's say he can do it in three weeks' time.
At the same time, application B (which dev B created) has an emergency. Dev B is occupied, but Dev C is available, even though he doesn't know the codebase. What do we do?
- If we keep B working on A, and put C to work on B, then we have two developers who don't know what they're doing, and the work is bering performed suboptimally.
- If we pull B away from A and have him do B, and we now put C on A, then all of developer B's work (or a significant portion of it) may end up being discarded. This is potentially days/weeks of effort wasted.
Dev A comes back from his holiday, and sees that B did not understand the code, and thus implemented it badly. It's not B's fault, because he used all available resources, the source code just wasn't adequately readable. Does A now have to spend time fixing the readability of the code?
All of these problems, and many more, end up wasting time. Yes, in the short term, clean code requires more effort now, but it will end up paying dividends in the future when inevitable bugs/changes need to be addressed.
Management needs to understand that a short task now will save you several long tasks in the future. Failing to plan is planning to fail.
If so, what are some arguments I can use to justify the fact that more LOC have been written?
My goto explanation is asking management what they would prefer: an application with a 100KLOC codebase that can be developed in three months, or a 50KLOC codebase that can be developed in six months.
They will obviously pick the shorter development time, because management doesn't care about KLOC. Managers who focus on KLOC are micromanaging while being uninformed about what they're trying to manage.
add a comment |
Considering the fact that the "is email valid" condition you currently have would accept the very much invalid email address "@
", I think you have every reason to abstract out an EmailValidator class. Even better, use a good, well-tested library to validate email addresses.
Lines of code as a metric is meaningless. The important questions in software engineering are not:
- Do you have too much code?
- Do you have too little code?
The important questions are:
- Is the application as a whole designed correctly?
- Is the code implemented correctly?
- Is the code maintainable?
- Is the code testable?
- Is the code adequately tested?
I've never given a thought to LoC when writing code for any purpose but Code Golf. I have asked myself "Could I write this more succinctly?", but for purposes of readability, maintainability, and efficiency, not simply length.
Sure, maybe I could use a long chain of boolean operations instead of a utility method, but should I?
Your question actually makes me think back on some long chains of booleans I've written and realize I probably should have written one or more utility method(s) instead.
add a comment |
On one level, they are right - less code is better.
Another answer quoted Gate, I prefer:
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
– Edsger Dijkstra
“When debugging, novices insert corrective code; experts remove defective code.”
– Richard Pattis
The cheapest, fastest, and most reliable components are those that aren’t there. - Gordon Bell
In short, the less code you have, the less can go wrong. If something isn't necessary, then cut it.
If there is over-complicated code, then simplify it until the actual functional elements are all that remain.
What is important here, is that these all refer to functionality, and only having the minimum required to do it. It doesn't say anything about how that is expressed.
What what you are doing by attempting to have clean code isn't against the above. You are adding to your LOC but not adding unused functionality.
The end goal is to have readable code but no superfluous extras. The two principles should not act against each other.
A metaphor would be building a car. The functional part of the code is the chassis, engine, wheels... what makes the car run. How you break that up is more like the upholstery, seats and so on, it makes it easier to handle.
You want your mechanics as simple as possible while still performing their job, to minimise the chance of things going wrong, but that doesn't prevent you from having nice seats.
add a comment |
I'd point out there is nothing inherently wrong with this:
if(contact.email != null && contact.email.contains('@')
At least assuming it's used this one time.
I could have problems with this very easily:
private Boolean isEmailValid(String email)
return contact.email != null && contact.email.contains('@');
A few things I'd watch for:
- Why is it private? It looks like a potentially useful stub. Is it useful enough to be a private method and no chance of it being used more widely?
- I wouldn't name the method IsValidEmail personally, possibly ContainsAtSign or LooksVaguelyLikeEmailAddress because it does almost no real validation, which is maybe good, maybe not what is exected.
- Is it being used more than once?
If it is being used once, is simple to parse, and takes less than one line I would second guess the decision. It probably isn't something I'd call out if it wasn't a particular problem from a team.
On the other hand I have seen methods do something like this:
if (contact.email != null && contact.email.contains('@')) ...
else if (contact.email != null && contact.email.contains('@') && contact.email.contains("@mydomain.com")) //headquarters email
else if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") ) //internal contract teams
That example is obviously not DRY.
Or even just that last statement can give another example:
if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") )
The goal should be to make the code more readable:
if (LooksSortaLikeAnEmail(contact.Email)) ...
else if (LooksLikeFromHeadquarters(contact.Email)) ...
else if (LooksLikeInternalEmail(contact.Email)) ...
Another scenario:
You might have a method like:
public void SaveContact(Contact contact)
if (contact.email != null && contact.email.contains('@'))
contacts.Add(contact);
contacts.Save();
If this fits your business logic and isn't reused there is not a problem here.
But when someone asks "Why is '@' saved, because that's not right!" and you decide to add actual validation of some sort, then extract it!
You'll be glad you did when you also need to account for the presidents second email account Pr3$sid3nt@h0m3!@mydomain.com and decide to just go all out and try and support RFC 2822.
On readability:
// If there is an email property and it contains an @ sign then process
if (contact.email != null && contact.email.contains('@'))
If your code is this clear, you don't need comments here. In fact, you don't need comments to say what the code is doing most the time, but rather why it's doing it:
// The UI passes '@' by default, the DBA's made this column non-nullable but
// marketing is currently more concerned with other fields and '@' default is OK
if (contact.email != null && contact.email.contains('@'))
Whether the comments above an if statement or inside a tiny method is to me, pedantic. I might even argue the opposite of useful with good comments inside another method because now you would have to navigate to another method to see how and why it does what it does.
In summary: Don't measure these things; Focus on the principles that the text was built from (DRY, SOLID, KISS).
// A valid class that does nothing
public class Nothing
add a comment |
There's lots of wisdom in the existing answers, but I'd like to add in one more factor: the language.
Some languages take more code than others to get the same effect. In particular, while Java (which I suspect is the language in the question) is extremely well-known and generally very solid and clear and straightforward, some more modern languages are much more concise and expressive.
For example, in Java it could easily take 50 lines to write a new class with three properties, each with a getter and setter, and one or more constructors — while you can accomplish exactly the same in a single line of Kotlin* or Scala. (Even greater saving if you also wanted suitable equals()
, hashCode()
, and toString()
methods.)
The result is that in Java, the extra work means you're more likely to reuse a general object that doesn't really fit, to squeeze properties into existing objects, or to pass a bunch of ‘bare’ properties around individually; while in a concise, expressive language, you're more likely to write better code.
(This highlights the difference between the ‘surface’ complexity of the code, and the complexity of the ideas/models/processing it implements. Lines of code isn't a bad measure of the first, but has much less to do with the second.)
So the ‘cost’ of doing things right depends on the language. Perhaps one sign of a good language is one that doesn't make you choose between doing things well, and doing them simply!
(* This isn't really the place for a plug, but Kotlin is well worth a look IMHO.)
add a comment |
Clean Code is an excellent book, and well worth reading, but it is not the final authority on such matters.
Breaking code down into logical functions is usually a good idea, but few programmers do it to the extent that Martin does - at some point you get diminishing returns from turning everything into functions and it can get hard to follow when all the code is in tiny pieces.
One option when it's not worth creating a whole new function is to simply use an intermediate variable:
boolean isEmailValid = (contact.email != null && contact.emails.contains('@');
if (isEmailValid) {
...
This helps keep the code easy to follow without having to jump around the file a lot.
Another issue is that Clean Code is getting quite old as a book now. A lot of software engineering has moved in the direction of functional programming, whereas Martin goes out of his way to add state to things and create objects. I suspect he would have written quite a different book if he'd written it today.
add a comment |
Let's assume that you are working with class Contact
currently. The fact that you are writing another method for validation of email address is evidence of the fact that the class Contact
is not handling a single responsibility.
It is also handling some email responsibility, which ideally, should be its own class.
Further proof that your code is a fusion of Contact
and Email
class is that you will not be able to test email validation code easily. It will require a lot of maneuverings to reach email validation code in a big method with the right values. See the method viz below.
private void LargeMethod()
//A lot of code which modifies a lot of values. You do all sorts of tricks here.
//Code.
//Code..
//Code...
//Email validation code becoming very difficult to test as it will be difficult to ensure
//that you have the right data till you reach here in the method
ValidateEmail();
//Another whole lot of code that modifies all sorts of values.
//Extra work to preserve the result of ValidateEmail() for your asserts later.
On the other hand, if you had a separate Email class with a method for email validation, then to unit test your validation code you would just make one simple call to Email.Validation()
with your test data.
Bonus Content: MFeather's talk about the deep synergy between testability and good design.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "131"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: false,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
CRDev is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f388802%2fhow-do-you-justify-more-code-being-written-by-following-clean-code-practices%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
StackExchange.ready(function ()
$("#show-editor-button input, #show-editor-button button").click(function ()
var showEditor = function()
$("#show-editor-button").hide();
$("#post-form").removeClass("dno");
StackExchange.editor.finallyInit();
;
var useFancy = $(this).data('confirm-use-fancy');
if(useFancy == 'True')
var popupTitle = $(this).data('confirm-fancy-title');
var popupBody = $(this).data('confirm-fancy-body');
var popupAccept = $(this).data('confirm-fancy-accept-button');
$(this).loadPopup(
url: '/post/self-answer-popup',
loaded: function(popup)
var pTitle = $(popup).find('h2');
var pBody = $(popup).find('.popup-body');
var pSubmit = $(popup).find('.popup-submit');
pTitle.text(popupTitle);
pBody.html(popupBody);
pSubmit.val(popupAccept).click(showEditor);
)
else
var confirmText = $(this).data('confirm-text');
if (confirmText ? confirm(confirmText) : true)
showEditor();
);
);
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
... we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain
These folk have correctly identified something: they want the code to be easier to maintain. Where they've gone wrong though is assuming that the less code there is, the easier it is to maintain.
For code to be easy to maintain, then it needs to be easy to change. By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one. Tests are code, so writing those tests is going to swell your code base. And that is a good thing.
Secondly, in order to work out what needs changing, you code needs to be both easy to read and easy to reason about. Very terse code, shrunk in size just to keep the line count down is very unlikely to be easy to read. There's obviously a compromise to be struck as longer code will take longer to read. But if it's quicker to understand, then it's worth it. If it doesn't offer that benefit, then that verbosity stops being a benefit. But if longer code improves readability then again this is a good thing.
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
|
show 11 more comments
... we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain
These folk have correctly identified something: they want the code to be easier to maintain. Where they've gone wrong though is assuming that the less code there is, the easier it is to maintain.
For code to be easy to maintain, then it needs to be easy to change. By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one. Tests are code, so writing those tests is going to swell your code base. And that is a good thing.
Secondly, in order to work out what needs changing, you code needs to be both easy to read and easy to reason about. Very terse code, shrunk in size just to keep the line count down is very unlikely to be easy to read. There's obviously a compromise to be struck as longer code will take longer to read. But if it's quicker to understand, then it's worth it. If it doesn't offer that benefit, then that verbosity stops being a benefit. But if longer code improves readability then again this is a good thing.
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
|
show 11 more comments
... we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain
These folk have correctly identified something: they want the code to be easier to maintain. Where they've gone wrong though is assuming that the less code there is, the easier it is to maintain.
For code to be easy to maintain, then it needs to be easy to change. By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one. Tests are code, so writing those tests is going to swell your code base. And that is a good thing.
Secondly, in order to work out what needs changing, you code needs to be both easy to read and easy to reason about. Very terse code, shrunk in size just to keep the line count down is very unlikely to be easy to read. There's obviously a compromise to be struck as longer code will take longer to read. But if it's quicker to understand, then it's worth it. If it doesn't offer that benefit, then that verbosity stops being a benefit. But if longer code improves readability then again this is a good thing.
... we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain
These folk have correctly identified something: they want the code to be easier to maintain. Where they've gone wrong though is assuming that the less code there is, the easier it is to maintain.
For code to be easy to maintain, then it needs to be easy to change. By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one. Tests are code, so writing those tests is going to swell your code base. And that is a good thing.
Secondly, in order to work out what needs changing, you code needs to be both easy to read and easy to reason about. Very terse code, shrunk in size just to keep the line count down is very unlikely to be easy to read. There's obviously a compromise to be struck as longer code will take longer to read. But if it's quicker to understand, then it's worth it. If it doesn't offer that benefit, then that verbosity stops being a benefit. But if longer code improves readability then again this is a good thing.
answered 14 hours ago
David ArnoDavid Arno
28k65591
28k65591
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
|
show 11 more comments
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
6
6
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
"By far the easiest way to achieve easy-to-change code is to have a full set of automated tests for it that will fail if your change is a breaking one." This is simply not true. Tests require additional work for every behavioural change because the tests also need changing, this is by design and many would argue makes the change safer, but it also necessarily makes changes harder.
– Jack Aidley
14 hours ago
25
25
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
Sure, but the time lost in maintaining these tests is dwarfed by the time you would have lost diagnosing and fixing bugs that the tests prevent.
– MetaFight
14 hours ago
9
9
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
@JackAidley, having to change the tests along with the code might give the appearance of more work, but only if one ignores the hard-to-find bugs that changes to untested code will introduce and that often won't be found until after shipping. The latter merely offers the illusion of less work.
– David Arno
14 hours ago
12
12
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
@JackAidley, I completely disagree with you. Tests make code easier to change. I'll concede though that badly designed code that's too tightly coupled and thus coupled tightly to tests can be hard to change, but well structured, well tested code is simple to change in my experience.
– David Arno
13 hours ago
7
7
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
@JackAidley You can refactor a lot without changing any API or interface. It means you can go crazy while modifying the code without having to change a single line in unit or functional tests. That is, if your tests don't test a specific implementation.
– Eric Duminil
13 hours ago
|
show 11 more comments
Yes, it's an acceptable byproduct, and the justification is that it is now structured such that you don't have to read most of the code most of the time. Instead of reading a 30-line function every single time you are making a change, you are reading a 5-line function to get the overall flow, and maybe a couple of the helper functions if your change touches that area. If your new "extra" class is called EmailValidator
and you know your problem isn't with email validation, you can skip reading it altogether.
It's also easier to reuse smaller pieces, which tends to reduce your line count for your overall program. An EmailValidator
can be used all over the place. Some lines of code that do email validation but are scrunched together with database access code can't be reused.
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
add a comment |
Yes, it's an acceptable byproduct, and the justification is that it is now structured such that you don't have to read most of the code most of the time. Instead of reading a 30-line function every single time you are making a change, you are reading a 5-line function to get the overall flow, and maybe a couple of the helper functions if your change touches that area. If your new "extra" class is called EmailValidator
and you know your problem isn't with email validation, you can skip reading it altogether.
It's also easier to reuse smaller pieces, which tends to reduce your line count for your overall program. An EmailValidator
can be used all over the place. Some lines of code that do email validation but are scrunched together with database access code can't be reused.
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
add a comment |
Yes, it's an acceptable byproduct, and the justification is that it is now structured such that you don't have to read most of the code most of the time. Instead of reading a 30-line function every single time you are making a change, you are reading a 5-line function to get the overall flow, and maybe a couple of the helper functions if your change touches that area. If your new "extra" class is called EmailValidator
and you know your problem isn't with email validation, you can skip reading it altogether.
It's also easier to reuse smaller pieces, which tends to reduce your line count for your overall program. An EmailValidator
can be used all over the place. Some lines of code that do email validation but are scrunched together with database access code can't be reused.
Yes, it's an acceptable byproduct, and the justification is that it is now structured such that you don't have to read most of the code most of the time. Instead of reading a 30-line function every single time you are making a change, you are reading a 5-line function to get the overall flow, and maybe a couple of the helper functions if your change touches that area. If your new "extra" class is called EmailValidator
and you know your problem isn't with email validation, you can skip reading it altogether.
It's also easier to reuse smaller pieces, which tends to reduce your line count for your overall program. An EmailValidator
can be used all over the place. Some lines of code that do email validation but are scrunched together with database access code can't be reused.
answered 14 hours ago
Karl BielefeldtKarl Bielefeldt
120k30214412
120k30214412
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
add a comment |
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
12
12
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
It might be good to also add to the last line a note about how it not only can't be reused, but if the rules change for what defines a valid email, you'd have to find every place that you check for a valid e-mail to change the code and hope you catch it all
– Taegost
11 hours ago
add a comment |
Bill Gates was famously attributed as saying, "Measuring programming progress by lines of code is like measuring aircraft building progress by weight."
I humbly agree with this sentiment. This is to not say that a program should strive for more or less lines of code, but that this isn't ultimately what counts to create a functioning and working program. It helps to remember that ultimately the reason behind adding extra lines of code is that it is theoretically more readable that way.
Disagreements can be had on whether a specific change is more or less readable, but I don't think you'd be wrong to make a change to your program because you think by doing so you're making it more readable. For instance making an isEmailValid
could be thought to be superfluous and unnecessary, especially if it is being called exactly once by the class which defines it. However I would much rather see an isEmailValid
in a condition than a string of ANDed conditions whereby I must determine what each individual condition checks and why it is being checked.
Where you get into trouble is when you create a isEmailValid
method which has side effects or checks things other than the e-mail, because this is worse than simply writing it all out. It is worse because it is misleading and I may miss a bug because of it.
Though clearly you're not doing that in this case, so I would encourage you to continue as you're doing. You should always ask yourself if by making the change, it is easier to read, and if that is your case, then do it!
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
add a comment |
Bill Gates was famously attributed as saying, "Measuring programming progress by lines of code is like measuring aircraft building progress by weight."
I humbly agree with this sentiment. This is to not say that a program should strive for more or less lines of code, but that this isn't ultimately what counts to create a functioning and working program. It helps to remember that ultimately the reason behind adding extra lines of code is that it is theoretically more readable that way.
Disagreements can be had on whether a specific change is more or less readable, but I don't think you'd be wrong to make a change to your program because you think by doing so you're making it more readable. For instance making an isEmailValid
could be thought to be superfluous and unnecessary, especially if it is being called exactly once by the class which defines it. However I would much rather see an isEmailValid
in a condition than a string of ANDed conditions whereby I must determine what each individual condition checks and why it is being checked.
Where you get into trouble is when you create a isEmailValid
method which has side effects or checks things other than the e-mail, because this is worse than simply writing it all out. It is worse because it is misleading and I may miss a bug because of it.
Though clearly you're not doing that in this case, so I would encourage you to continue as you're doing. You should always ask yourself if by making the change, it is easier to read, and if that is your case, then do it!
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
add a comment |
Bill Gates was famously attributed as saying, "Measuring programming progress by lines of code is like measuring aircraft building progress by weight."
I humbly agree with this sentiment. This is to not say that a program should strive for more or less lines of code, but that this isn't ultimately what counts to create a functioning and working program. It helps to remember that ultimately the reason behind adding extra lines of code is that it is theoretically more readable that way.
Disagreements can be had on whether a specific change is more or less readable, but I don't think you'd be wrong to make a change to your program because you think by doing so you're making it more readable. For instance making an isEmailValid
could be thought to be superfluous and unnecessary, especially if it is being called exactly once by the class which defines it. However I would much rather see an isEmailValid
in a condition than a string of ANDed conditions whereby I must determine what each individual condition checks and why it is being checked.
Where you get into trouble is when you create a isEmailValid
method which has side effects or checks things other than the e-mail, because this is worse than simply writing it all out. It is worse because it is misleading and I may miss a bug because of it.
Though clearly you're not doing that in this case, so I would encourage you to continue as you're doing. You should always ask yourself if by making the change, it is easier to read, and if that is your case, then do it!
Bill Gates was famously attributed as saying, "Measuring programming progress by lines of code is like measuring aircraft building progress by weight."
I humbly agree with this sentiment. This is to not say that a program should strive for more or less lines of code, but that this isn't ultimately what counts to create a functioning and working program. It helps to remember that ultimately the reason behind adding extra lines of code is that it is theoretically more readable that way.
Disagreements can be had on whether a specific change is more or less readable, but I don't think you'd be wrong to make a change to your program because you think by doing so you're making it more readable. For instance making an isEmailValid
could be thought to be superfluous and unnecessary, especially if it is being called exactly once by the class which defines it. However I would much rather see an isEmailValid
in a condition than a string of ANDed conditions whereby I must determine what each individual condition checks and why it is being checked.
Where you get into trouble is when you create a isEmailValid
method which has side effects or checks things other than the e-mail, because this is worse than simply writing it all out. It is worse because it is misleading and I may miss a bug because of it.
Though clearly you're not doing that in this case, so I would encourage you to continue as you're doing. You should always ask yourself if by making the change, it is easier to read, and if that is your case, then do it!
answered 14 hours ago
NeilNeil
20.3k3668
20.3k3668
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
add a comment |
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
Aircraft weight is an important metric, though. And during the design the expected weight is monitored closely. Not as a sign of progress, but as a constraint. Monitoring lines of code suggest more is better, while in aircraft design less weight is better. So I think mister Gates could have chosen a better illustration for his point.
– jos
13 hours ago
9
9
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
@jos on the particular team OP is working with, it appears fewer LOC is deemed 'better'. The point that Bill Gates was making is that LOC is not related to progress in any meaningful way, just like in aircraft construction weight is not related to progress in a meaningful way. An aircraft under construction may have 95% of its final weight relatively quickly, but it would just be an empty shell with no control systems it, it is not 95% complete. Same in software, if a program has 100k lines of code, that doesn't mean each 1000 lines provides 1% of the functionality.
– Mr.Mindor
12 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
Progress monitoring is a tough job, isn't it? Poor managers.
– jos
11 hours ago
add a comment |
so some developers/managers see value in writing less code to get things done so that we have less code to maintain
This is a matter of losing sight on the actual goal.
What matters is lowering hours spent on development. That is measured in time (or equivalent effort), not in lines of code.
This is like saying that car manufacturers should build their cars with less screws, because it takes a non-zero amount of time to put each screw in. While that is pedantically correct, a car's market value is not defined by how many screws it does or doesn't have. Above all else, a car needs to be performant, safe, and easy to maintain.
The rest of the answer are examples of how clean code can lead to time gains.
Logging
Take an application (A) which has no logging. Now create application B, which is the same application A but with logging. B will always have more lines of code, and thus you need to write more code.
But a lot of time will sink into investigating issues and bugs, and figuring out what went wrong.
For application A, developers will be stuck reading the code, and having to continually reproduce the problem and step through the code to find the source of the issue. This means that the developer has to test from the beginning of the execution to the end, in every used layer, and needs to observe every used piece of logic.
Maybe he is lucky to find it immediately, but maybe the answer is going to be in the last place he thinks of looking.
For application B, assuming perfect logging, a developer observes the logs, can immediately identify the faulty component, and now knows where to look.
This can be a matter of minutes, hours or days saved; depending on the size and complexity of the codebase.
Regressions
Take application A, which is not DRY-friendly at all.
Take application B, which is DRY, but ended up needing more lines because of the additional abstractions.
A change request is filed, which requires a change to the logic.
For application B, the developer changes the (unique, shared) logic according to the change request.
For application A, the developer has to change all instances of this logic where he remembers it being used.
- If he manages to remember all instances, he'll still have to implement the same change several times.
- If he does not manage to remember all instances, you're now dealing with an inconsistent codebase that contradicts itself. If the developer forgot a rarely used piece of code, this bug may not become apparent to the end users until well into the future. At that time, are the end users going to identify what the source of the issue is? Even if so, the developer may not remember what the change entailed, and will have to figure out how to change this forgotten piece of logic. Maybe the developer doesn't even work at the company by then, and then someone else now has to figure it all out from scratch.
This can lead to enormous time wastage. Not just in development, but in hunting and finding the bug. The application can start behaving erratically in a way that developers cannot easily comprehend. And that will lead to lengthy debugging sessions.
Developer interchangeability
Developer A created application A. The code is not clean nor readable, but it works like a charm and has been running in production. Unsurprisingly, there is no documentation either.
Developer A is absent for a month due to holidays. An emergency change request is filed. It can't wait another three weeks for Dev A to return.
Developer B has to execute this change. He now needs to read the entire codebase, understand how everything works, why it works, and what it tries to accomplish. This takes ages, but let's say he can do it in three weeks' time.
At the same time, application B (which dev B created) has an emergency. Dev B is occupied, but Dev C is available, even though he doesn't know the codebase. What do we do?
- If we keep B working on A, and put C to work on B, then we have two developers who don't know what they're doing, and the work is bering performed suboptimally.
- If we pull B away from A and have him do B, and we now put C on A, then all of developer B's work (or a significant portion of it) may end up being discarded. This is potentially days/weeks of effort wasted.
Dev A comes back from his holiday, and sees that B did not understand the code, and thus implemented it badly. It's not B's fault, because he used all available resources, the source code just wasn't adequately readable. Does A now have to spend time fixing the readability of the code?
All of these problems, and many more, end up wasting time. Yes, in the short term, clean code requires more effort now, but it will end up paying dividends in the future when inevitable bugs/changes need to be addressed.
Management needs to understand that a short task now will save you several long tasks in the future. Failing to plan is planning to fail.
If so, what are some arguments I can use to justify the fact that more LOC have been written?
My goto explanation is asking management what they would prefer: an application with a 100KLOC codebase that can be developed in three months, or a 50KLOC codebase that can be developed in six months.
They will obviously pick the shorter development time, because management doesn't care about KLOC. Managers who focus on KLOC are micromanaging while being uninformed about what they're trying to manage.
add a comment |
so some developers/managers see value in writing less code to get things done so that we have less code to maintain
This is a matter of losing sight on the actual goal.
What matters is lowering hours spent on development. That is measured in time (or equivalent effort), not in lines of code.
This is like saying that car manufacturers should build their cars with less screws, because it takes a non-zero amount of time to put each screw in. While that is pedantically correct, a car's market value is not defined by how many screws it does or doesn't have. Above all else, a car needs to be performant, safe, and easy to maintain.
The rest of the answer are examples of how clean code can lead to time gains.
Logging
Take an application (A) which has no logging. Now create application B, which is the same application A but with logging. B will always have more lines of code, and thus you need to write more code.
But a lot of time will sink into investigating issues and bugs, and figuring out what went wrong.
For application A, developers will be stuck reading the code, and having to continually reproduce the problem and step through the code to find the source of the issue. This means that the developer has to test from the beginning of the execution to the end, in every used layer, and needs to observe every used piece of logic.
Maybe he is lucky to find it immediately, but maybe the answer is going to be in the last place he thinks of looking.
For application B, assuming perfect logging, a developer observes the logs, can immediately identify the faulty component, and now knows where to look.
This can be a matter of minutes, hours or days saved; depending on the size and complexity of the codebase.
Regressions
Take application A, which is not DRY-friendly at all.
Take application B, which is DRY, but ended up needing more lines because of the additional abstractions.
A change request is filed, which requires a change to the logic.
For application B, the developer changes the (unique, shared) logic according to the change request.
For application A, the developer has to change all instances of this logic where he remembers it being used.
- If he manages to remember all instances, he'll still have to implement the same change several times.
- If he does not manage to remember all instances, you're now dealing with an inconsistent codebase that contradicts itself. If the developer forgot a rarely used piece of code, this bug may not become apparent to the end users until well into the future. At that time, are the end users going to identify what the source of the issue is? Even if so, the developer may not remember what the change entailed, and will have to figure out how to change this forgotten piece of logic. Maybe the developer doesn't even work at the company by then, and then someone else now has to figure it all out from scratch.
This can lead to enormous time wastage. Not just in development, but in hunting and finding the bug. The application can start behaving erratically in a way that developers cannot easily comprehend. And that will lead to lengthy debugging sessions.
Developer interchangeability
Developer A created application A. The code is not clean nor readable, but it works like a charm and has been running in production. Unsurprisingly, there is no documentation either.
Developer A is absent for a month due to holidays. An emergency change request is filed. It can't wait another three weeks for Dev A to return.
Developer B has to execute this change. He now needs to read the entire codebase, understand how everything works, why it works, and what it tries to accomplish. This takes ages, but let's say he can do it in three weeks' time.
At the same time, application B (which dev B created) has an emergency. Dev B is occupied, but Dev C is available, even though he doesn't know the codebase. What do we do?
- If we keep B working on A, and put C to work on B, then we have two developers who don't know what they're doing, and the work is bering performed suboptimally.
- If we pull B away from A and have him do B, and we now put C on A, then all of developer B's work (or a significant portion of it) may end up being discarded. This is potentially days/weeks of effort wasted.
Dev A comes back from his holiday, and sees that B did not understand the code, and thus implemented it badly. It's not B's fault, because he used all available resources, the source code just wasn't adequately readable. Does A now have to spend time fixing the readability of the code?
All of these problems, and many more, end up wasting time. Yes, in the short term, clean code requires more effort now, but it will end up paying dividends in the future when inevitable bugs/changes need to be addressed.
Management needs to understand that a short task now will save you several long tasks in the future. Failing to plan is planning to fail.
If so, what are some arguments I can use to justify the fact that more LOC have been written?
My goto explanation is asking management what they would prefer: an application with a 100KLOC codebase that can be developed in three months, or a 50KLOC codebase that can be developed in six months.
They will obviously pick the shorter development time, because management doesn't care about KLOC. Managers who focus on KLOC are micromanaging while being uninformed about what they're trying to manage.
add a comment |
so some developers/managers see value in writing less code to get things done so that we have less code to maintain
This is a matter of losing sight on the actual goal.
What matters is lowering hours spent on development. That is measured in time (or equivalent effort), not in lines of code.
This is like saying that car manufacturers should build their cars with less screws, because it takes a non-zero amount of time to put each screw in. While that is pedantically correct, a car's market value is not defined by how many screws it does or doesn't have. Above all else, a car needs to be performant, safe, and easy to maintain.
The rest of the answer are examples of how clean code can lead to time gains.
Logging
Take an application (A) which has no logging. Now create application B, which is the same application A but with logging. B will always have more lines of code, and thus you need to write more code.
But a lot of time will sink into investigating issues and bugs, and figuring out what went wrong.
For application A, developers will be stuck reading the code, and having to continually reproduce the problem and step through the code to find the source of the issue. This means that the developer has to test from the beginning of the execution to the end, in every used layer, and needs to observe every used piece of logic.
Maybe he is lucky to find it immediately, but maybe the answer is going to be in the last place he thinks of looking.
For application B, assuming perfect logging, a developer observes the logs, can immediately identify the faulty component, and now knows where to look.
This can be a matter of minutes, hours or days saved; depending on the size and complexity of the codebase.
Regressions
Take application A, which is not DRY-friendly at all.
Take application B, which is DRY, but ended up needing more lines because of the additional abstractions.
A change request is filed, which requires a change to the logic.
For application B, the developer changes the (unique, shared) logic according to the change request.
For application A, the developer has to change all instances of this logic where he remembers it being used.
- If he manages to remember all instances, he'll still have to implement the same change several times.
- If he does not manage to remember all instances, you're now dealing with an inconsistent codebase that contradicts itself. If the developer forgot a rarely used piece of code, this bug may not become apparent to the end users until well into the future. At that time, are the end users going to identify what the source of the issue is? Even if so, the developer may not remember what the change entailed, and will have to figure out how to change this forgotten piece of logic. Maybe the developer doesn't even work at the company by then, and then someone else now has to figure it all out from scratch.
This can lead to enormous time wastage. Not just in development, but in hunting and finding the bug. The application can start behaving erratically in a way that developers cannot easily comprehend. And that will lead to lengthy debugging sessions.
Developer interchangeability
Developer A created application A. The code is not clean nor readable, but it works like a charm and has been running in production. Unsurprisingly, there is no documentation either.
Developer A is absent for a month due to holidays. An emergency change request is filed. It can't wait another three weeks for Dev A to return.
Developer B has to execute this change. He now needs to read the entire codebase, understand how everything works, why it works, and what it tries to accomplish. This takes ages, but let's say he can do it in three weeks' time.
At the same time, application B (which dev B created) has an emergency. Dev B is occupied, but Dev C is available, even though he doesn't know the codebase. What do we do?
- If we keep B working on A, and put C to work on B, then we have two developers who don't know what they're doing, and the work is bering performed suboptimally.
- If we pull B away from A and have him do B, and we now put C on A, then all of developer B's work (or a significant portion of it) may end up being discarded. This is potentially days/weeks of effort wasted.
Dev A comes back from his holiday, and sees that B did not understand the code, and thus implemented it badly. It's not B's fault, because he used all available resources, the source code just wasn't adequately readable. Does A now have to spend time fixing the readability of the code?
All of these problems, and many more, end up wasting time. Yes, in the short term, clean code requires more effort now, but it will end up paying dividends in the future when inevitable bugs/changes need to be addressed.
Management needs to understand that a short task now will save you several long tasks in the future. Failing to plan is planning to fail.
If so, what are some arguments I can use to justify the fact that more LOC have been written?
My goto explanation is asking management what they would prefer: an application with a 100KLOC codebase that can be developed in three months, or a 50KLOC codebase that can be developed in six months.
They will obviously pick the shorter development time, because management doesn't care about KLOC. Managers who focus on KLOC are micromanaging while being uninformed about what they're trying to manage.
so some developers/managers see value in writing less code to get things done so that we have less code to maintain
This is a matter of losing sight on the actual goal.
What matters is lowering hours spent on development. That is measured in time (or equivalent effort), not in lines of code.
This is like saying that car manufacturers should build their cars with less screws, because it takes a non-zero amount of time to put each screw in. While that is pedantically correct, a car's market value is not defined by how many screws it does or doesn't have. Above all else, a car needs to be performant, safe, and easy to maintain.
The rest of the answer are examples of how clean code can lead to time gains.
Logging
Take an application (A) which has no logging. Now create application B, which is the same application A but with logging. B will always have more lines of code, and thus you need to write more code.
But a lot of time will sink into investigating issues and bugs, and figuring out what went wrong.
For application A, developers will be stuck reading the code, and having to continually reproduce the problem and step through the code to find the source of the issue. This means that the developer has to test from the beginning of the execution to the end, in every used layer, and needs to observe every used piece of logic.
Maybe he is lucky to find it immediately, but maybe the answer is going to be in the last place he thinks of looking.
For application B, assuming perfect logging, a developer observes the logs, can immediately identify the faulty component, and now knows where to look.
This can be a matter of minutes, hours or days saved; depending on the size and complexity of the codebase.
Regressions
Take application A, which is not DRY-friendly at all.
Take application B, which is DRY, but ended up needing more lines because of the additional abstractions.
A change request is filed, which requires a change to the logic.
For application B, the developer changes the (unique, shared) logic according to the change request.
For application A, the developer has to change all instances of this logic where he remembers it being used.
- If he manages to remember all instances, he'll still have to implement the same change several times.
- If he does not manage to remember all instances, you're now dealing with an inconsistent codebase that contradicts itself. If the developer forgot a rarely used piece of code, this bug may not become apparent to the end users until well into the future. At that time, are the end users going to identify what the source of the issue is? Even if so, the developer may not remember what the change entailed, and will have to figure out how to change this forgotten piece of logic. Maybe the developer doesn't even work at the company by then, and then someone else now has to figure it all out from scratch.
This can lead to enormous time wastage. Not just in development, but in hunting and finding the bug. The application can start behaving erratically in a way that developers cannot easily comprehend. And that will lead to lengthy debugging sessions.
Developer interchangeability
Developer A created application A. The code is not clean nor readable, but it works like a charm and has been running in production. Unsurprisingly, there is no documentation either.
Developer A is absent for a month due to holidays. An emergency change request is filed. It can't wait another three weeks for Dev A to return.
Developer B has to execute this change. He now needs to read the entire codebase, understand how everything works, why it works, and what it tries to accomplish. This takes ages, but let's say he can do it in three weeks' time.
At the same time, application B (which dev B created) has an emergency. Dev B is occupied, but Dev C is available, even though he doesn't know the codebase. What do we do?
- If we keep B working on A, and put C to work on B, then we have two developers who don't know what they're doing, and the work is bering performed suboptimally.
- If we pull B away from A and have him do B, and we now put C on A, then all of developer B's work (or a significant portion of it) may end up being discarded. This is potentially days/weeks of effort wasted.
Dev A comes back from his holiday, and sees that B did not understand the code, and thus implemented it badly. It's not B's fault, because he used all available resources, the source code just wasn't adequately readable. Does A now have to spend time fixing the readability of the code?
All of these problems, and many more, end up wasting time. Yes, in the short term, clean code requires more effort now, but it will end up paying dividends in the future when inevitable bugs/changes need to be addressed.
Management needs to understand that a short task now will save you several long tasks in the future. Failing to plan is planning to fail.
If so, what are some arguments I can use to justify the fact that more LOC have been written?
My goto explanation is asking management what they would prefer: an application with a 100KLOC codebase that can be developed in three months, or a 50KLOC codebase that can be developed in six months.
They will obviously pick the shorter development time, because management doesn't care about KLOC. Managers who focus on KLOC are micromanaging while being uninformed about what they're trying to manage.
edited 11 hours ago
answered 11 hours ago
FlaterFlater
8,67331525
8,67331525
add a comment |
add a comment |
Considering the fact that the "is email valid" condition you currently have would accept the very much invalid email address "@
", I think you have every reason to abstract out an EmailValidator class. Even better, use a good, well-tested library to validate email addresses.
Lines of code as a metric is meaningless. The important questions in software engineering are not:
- Do you have too much code?
- Do you have too little code?
The important questions are:
- Is the application as a whole designed correctly?
- Is the code implemented correctly?
- Is the code maintainable?
- Is the code testable?
- Is the code adequately tested?
I've never given a thought to LoC when writing code for any purpose but Code Golf. I have asked myself "Could I write this more succinctly?", but for purposes of readability, maintainability, and efficiency, not simply length.
Sure, maybe I could use a long chain of boolean operations instead of a utility method, but should I?
Your question actually makes me think back on some long chains of booleans I've written and realize I probably should have written one or more utility method(s) instead.
add a comment |
Considering the fact that the "is email valid" condition you currently have would accept the very much invalid email address "@
", I think you have every reason to abstract out an EmailValidator class. Even better, use a good, well-tested library to validate email addresses.
Lines of code as a metric is meaningless. The important questions in software engineering are not:
- Do you have too much code?
- Do you have too little code?
The important questions are:
- Is the application as a whole designed correctly?
- Is the code implemented correctly?
- Is the code maintainable?
- Is the code testable?
- Is the code adequately tested?
I've never given a thought to LoC when writing code for any purpose but Code Golf. I have asked myself "Could I write this more succinctly?", but for purposes of readability, maintainability, and efficiency, not simply length.
Sure, maybe I could use a long chain of boolean operations instead of a utility method, but should I?
Your question actually makes me think back on some long chains of booleans I've written and realize I probably should have written one or more utility method(s) instead.
add a comment |
Considering the fact that the "is email valid" condition you currently have would accept the very much invalid email address "@
", I think you have every reason to abstract out an EmailValidator class. Even better, use a good, well-tested library to validate email addresses.
Lines of code as a metric is meaningless. The important questions in software engineering are not:
- Do you have too much code?
- Do you have too little code?
The important questions are:
- Is the application as a whole designed correctly?
- Is the code implemented correctly?
- Is the code maintainable?
- Is the code testable?
- Is the code adequately tested?
I've never given a thought to LoC when writing code for any purpose but Code Golf. I have asked myself "Could I write this more succinctly?", but for purposes of readability, maintainability, and efficiency, not simply length.
Sure, maybe I could use a long chain of boolean operations instead of a utility method, but should I?
Your question actually makes me think back on some long chains of booleans I've written and realize I probably should have written one or more utility method(s) instead.
Considering the fact that the "is email valid" condition you currently have would accept the very much invalid email address "@
", I think you have every reason to abstract out an EmailValidator class. Even better, use a good, well-tested library to validate email addresses.
Lines of code as a metric is meaningless. The important questions in software engineering are not:
- Do you have too much code?
- Do you have too little code?
The important questions are:
- Is the application as a whole designed correctly?
- Is the code implemented correctly?
- Is the code maintainable?
- Is the code testable?
- Is the code adequately tested?
I've never given a thought to LoC when writing code for any purpose but Code Golf. I have asked myself "Could I write this more succinctly?", but for purposes of readability, maintainability, and efficiency, not simply length.
Sure, maybe I could use a long chain of boolean operations instead of a utility method, but should I?
Your question actually makes me think back on some long chains of booleans I've written and realize I probably should have written one or more utility method(s) instead.
answered 11 hours ago
Clement CherlinClement Cherlin
1,175710
1,175710
add a comment |
add a comment |
On one level, they are right - less code is better.
Another answer quoted Gate, I prefer:
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
– Edsger Dijkstra
“When debugging, novices insert corrective code; experts remove defective code.”
– Richard Pattis
The cheapest, fastest, and most reliable components are those that aren’t there. - Gordon Bell
In short, the less code you have, the less can go wrong. If something isn't necessary, then cut it.
If there is over-complicated code, then simplify it until the actual functional elements are all that remain.
What is important here, is that these all refer to functionality, and only having the minimum required to do it. It doesn't say anything about how that is expressed.
What what you are doing by attempting to have clean code isn't against the above. You are adding to your LOC but not adding unused functionality.
The end goal is to have readable code but no superfluous extras. The two principles should not act against each other.
A metaphor would be building a car. The functional part of the code is the chassis, engine, wheels... what makes the car run. How you break that up is more like the upholstery, seats and so on, it makes it easier to handle.
You want your mechanics as simple as possible while still performing their job, to minimise the chance of things going wrong, but that doesn't prevent you from having nice seats.
add a comment |
On one level, they are right - less code is better.
Another answer quoted Gate, I prefer:
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
– Edsger Dijkstra
“When debugging, novices insert corrective code; experts remove defective code.”
– Richard Pattis
The cheapest, fastest, and most reliable components are those that aren’t there. - Gordon Bell
In short, the less code you have, the less can go wrong. If something isn't necessary, then cut it.
If there is over-complicated code, then simplify it until the actual functional elements are all that remain.
What is important here, is that these all refer to functionality, and only having the minimum required to do it. It doesn't say anything about how that is expressed.
What what you are doing by attempting to have clean code isn't against the above. You are adding to your LOC but not adding unused functionality.
The end goal is to have readable code but no superfluous extras. The two principles should not act against each other.
A metaphor would be building a car. The functional part of the code is the chassis, engine, wheels... what makes the car run. How you break that up is more like the upholstery, seats and so on, it makes it easier to handle.
You want your mechanics as simple as possible while still performing their job, to minimise the chance of things going wrong, but that doesn't prevent you from having nice seats.
add a comment |
On one level, they are right - less code is better.
Another answer quoted Gate, I prefer:
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
– Edsger Dijkstra
“When debugging, novices insert corrective code; experts remove defective code.”
– Richard Pattis
The cheapest, fastest, and most reliable components are those that aren’t there. - Gordon Bell
In short, the less code you have, the less can go wrong. If something isn't necessary, then cut it.
If there is over-complicated code, then simplify it until the actual functional elements are all that remain.
What is important here, is that these all refer to functionality, and only having the minimum required to do it. It doesn't say anything about how that is expressed.
What what you are doing by attempting to have clean code isn't against the above. You are adding to your LOC but not adding unused functionality.
The end goal is to have readable code but no superfluous extras. The two principles should not act against each other.
A metaphor would be building a car. The functional part of the code is the chassis, engine, wheels... what makes the car run. How you break that up is more like the upholstery, seats and so on, it makes it easier to handle.
You want your mechanics as simple as possible while still performing their job, to minimise the chance of things going wrong, but that doesn't prevent you from having nice seats.
On one level, they are right - less code is better.
Another answer quoted Gate, I prefer:
“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”
– Edsger Dijkstra
“When debugging, novices insert corrective code; experts remove defective code.”
– Richard Pattis
The cheapest, fastest, and most reliable components are those that aren’t there. - Gordon Bell
In short, the less code you have, the less can go wrong. If something isn't necessary, then cut it.
If there is over-complicated code, then simplify it until the actual functional elements are all that remain.
What is important here, is that these all refer to functionality, and only having the minimum required to do it. It doesn't say anything about how that is expressed.
What what you are doing by attempting to have clean code isn't against the above. You are adding to your LOC but not adding unused functionality.
The end goal is to have readable code but no superfluous extras. The two principles should not act against each other.
A metaphor would be building a car. The functional part of the code is the chassis, engine, wheels... what makes the car run. How you break that up is more like the upholstery, seats and so on, it makes it easier to handle.
You want your mechanics as simple as possible while still performing their job, to minimise the chance of things going wrong, but that doesn't prevent you from having nice seats.
edited 11 hours ago
answered 11 hours ago
BaldrickkBaldrickk
556310
556310
add a comment |
add a comment |
I'd point out there is nothing inherently wrong with this:
if(contact.email != null && contact.email.contains('@')
At least assuming it's used this one time.
I could have problems with this very easily:
private Boolean isEmailValid(String email)
return contact.email != null && contact.email.contains('@');
A few things I'd watch for:
- Why is it private? It looks like a potentially useful stub. Is it useful enough to be a private method and no chance of it being used more widely?
- I wouldn't name the method IsValidEmail personally, possibly ContainsAtSign or LooksVaguelyLikeEmailAddress because it does almost no real validation, which is maybe good, maybe not what is exected.
- Is it being used more than once?
If it is being used once, is simple to parse, and takes less than one line I would second guess the decision. It probably isn't something I'd call out if it wasn't a particular problem from a team.
On the other hand I have seen methods do something like this:
if (contact.email != null && contact.email.contains('@')) ...
else if (contact.email != null && contact.email.contains('@') && contact.email.contains("@mydomain.com")) //headquarters email
else if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") ) //internal contract teams
That example is obviously not DRY.
Or even just that last statement can give another example:
if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") )
The goal should be to make the code more readable:
if (LooksSortaLikeAnEmail(contact.Email)) ...
else if (LooksLikeFromHeadquarters(contact.Email)) ...
else if (LooksLikeInternalEmail(contact.Email)) ...
Another scenario:
You might have a method like:
public void SaveContact(Contact contact)
if (contact.email != null && contact.email.contains('@'))
contacts.Add(contact);
contacts.Save();
If this fits your business logic and isn't reused there is not a problem here.
But when someone asks "Why is '@' saved, because that's not right!" and you decide to add actual validation of some sort, then extract it!
You'll be glad you did when you also need to account for the presidents second email account Pr3$sid3nt@h0m3!@mydomain.com and decide to just go all out and try and support RFC 2822.
On readability:
// If there is an email property and it contains an @ sign then process
if (contact.email != null && contact.email.contains('@'))
If your code is this clear, you don't need comments here. In fact, you don't need comments to say what the code is doing most the time, but rather why it's doing it:
// The UI passes '@' by default, the DBA's made this column non-nullable but
// marketing is currently more concerned with other fields and '@' default is OK
if (contact.email != null && contact.email.contains('@'))
Whether the comments above an if statement or inside a tiny method is to me, pedantic. I might even argue the opposite of useful with good comments inside another method because now you would have to navigate to another method to see how and why it does what it does.
In summary: Don't measure these things; Focus on the principles that the text was built from (DRY, SOLID, KISS).
// A valid class that does nothing
public class Nothing
add a comment |
I'd point out there is nothing inherently wrong with this:
if(contact.email != null && contact.email.contains('@')
At least assuming it's used this one time.
I could have problems with this very easily:
private Boolean isEmailValid(String email)
return contact.email != null && contact.email.contains('@');
A few things I'd watch for:
- Why is it private? It looks like a potentially useful stub. Is it useful enough to be a private method and no chance of it being used more widely?
- I wouldn't name the method IsValidEmail personally, possibly ContainsAtSign or LooksVaguelyLikeEmailAddress because it does almost no real validation, which is maybe good, maybe not what is exected.
- Is it being used more than once?
If it is being used once, is simple to parse, and takes less than one line I would second guess the decision. It probably isn't something I'd call out if it wasn't a particular problem from a team.
On the other hand I have seen methods do something like this:
if (contact.email != null && contact.email.contains('@')) ...
else if (contact.email != null && contact.email.contains('@') && contact.email.contains("@mydomain.com")) //headquarters email
else if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") ) //internal contract teams
That example is obviously not DRY.
Or even just that last statement can give another example:
if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") )
The goal should be to make the code more readable:
if (LooksSortaLikeAnEmail(contact.Email)) ...
else if (LooksLikeFromHeadquarters(contact.Email)) ...
else if (LooksLikeInternalEmail(contact.Email)) ...
Another scenario:
You might have a method like:
public void SaveContact(Contact contact)
if (contact.email != null && contact.email.contains('@'))
contacts.Add(contact);
contacts.Save();
If this fits your business logic and isn't reused there is not a problem here.
But when someone asks "Why is '@' saved, because that's not right!" and you decide to add actual validation of some sort, then extract it!
You'll be glad you did when you also need to account for the presidents second email account Pr3$sid3nt@h0m3!@mydomain.com and decide to just go all out and try and support RFC 2822.
On readability:
// If there is an email property and it contains an @ sign then process
if (contact.email != null && contact.email.contains('@'))
If your code is this clear, you don't need comments here. In fact, you don't need comments to say what the code is doing most the time, but rather why it's doing it:
// The UI passes '@' by default, the DBA's made this column non-nullable but
// marketing is currently more concerned with other fields and '@' default is OK
if (contact.email != null && contact.email.contains('@'))
Whether the comments above an if statement or inside a tiny method is to me, pedantic. I might even argue the opposite of useful with good comments inside another method because now you would have to navigate to another method to see how and why it does what it does.
In summary: Don't measure these things; Focus on the principles that the text was built from (DRY, SOLID, KISS).
// A valid class that does nothing
public class Nothing
add a comment |
I'd point out there is nothing inherently wrong with this:
if(contact.email != null && contact.email.contains('@')
At least assuming it's used this one time.
I could have problems with this very easily:
private Boolean isEmailValid(String email)
return contact.email != null && contact.email.contains('@');
A few things I'd watch for:
- Why is it private? It looks like a potentially useful stub. Is it useful enough to be a private method and no chance of it being used more widely?
- I wouldn't name the method IsValidEmail personally, possibly ContainsAtSign or LooksVaguelyLikeEmailAddress because it does almost no real validation, which is maybe good, maybe not what is exected.
- Is it being used more than once?
If it is being used once, is simple to parse, and takes less than one line I would second guess the decision. It probably isn't something I'd call out if it wasn't a particular problem from a team.
On the other hand I have seen methods do something like this:
if (contact.email != null && contact.email.contains('@')) ...
else if (contact.email != null && contact.email.contains('@') && contact.email.contains("@mydomain.com")) //headquarters email
else if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") ) //internal contract teams
That example is obviously not DRY.
Or even just that last statement can give another example:
if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") )
The goal should be to make the code more readable:
if (LooksSortaLikeAnEmail(contact.Email)) ...
else if (LooksLikeFromHeadquarters(contact.Email)) ...
else if (LooksLikeInternalEmail(contact.Email)) ...
Another scenario:
You might have a method like:
public void SaveContact(Contact contact)
if (contact.email != null && contact.email.contains('@'))
contacts.Add(contact);
contacts.Save();
If this fits your business logic and isn't reused there is not a problem here.
But when someone asks "Why is '@' saved, because that's not right!" and you decide to add actual validation of some sort, then extract it!
You'll be glad you did when you also need to account for the presidents second email account Pr3$sid3nt@h0m3!@mydomain.com and decide to just go all out and try and support RFC 2822.
On readability:
// If there is an email property and it contains an @ sign then process
if (contact.email != null && contact.email.contains('@'))
If your code is this clear, you don't need comments here. In fact, you don't need comments to say what the code is doing most the time, but rather why it's doing it:
// The UI passes '@' by default, the DBA's made this column non-nullable but
// marketing is currently more concerned with other fields and '@' default is OK
if (contact.email != null && contact.email.contains('@'))
Whether the comments above an if statement or inside a tiny method is to me, pedantic. I might even argue the opposite of useful with good comments inside another method because now you would have to navigate to another method to see how and why it does what it does.
In summary: Don't measure these things; Focus on the principles that the text was built from (DRY, SOLID, KISS).
// A valid class that does nothing
public class Nothing
I'd point out there is nothing inherently wrong with this:
if(contact.email != null && contact.email.contains('@')
At least assuming it's used this one time.
I could have problems with this very easily:
private Boolean isEmailValid(String email)
return contact.email != null && contact.email.contains('@');
A few things I'd watch for:
- Why is it private? It looks like a potentially useful stub. Is it useful enough to be a private method and no chance of it being used more widely?
- I wouldn't name the method IsValidEmail personally, possibly ContainsAtSign or LooksVaguelyLikeEmailAddress because it does almost no real validation, which is maybe good, maybe not what is exected.
- Is it being used more than once?
If it is being used once, is simple to parse, and takes less than one line I would second guess the decision. It probably isn't something I'd call out if it wasn't a particular problem from a team.
On the other hand I have seen methods do something like this:
if (contact.email != null && contact.email.contains('@')) ...
else if (contact.email != null && contact.email.contains('@') && contact.email.contains("@mydomain.com")) //headquarters email
else if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") ) //internal contract teams
That example is obviously not DRY.
Or even just that last statement can give another example:
if (contact.email != null && contact.email.contains('@') && (contact.email.contains("@news.mydomain.com") || contact.email.contains("@design.mydomain.com") )
The goal should be to make the code more readable:
if (LooksSortaLikeAnEmail(contact.Email)) ...
else if (LooksLikeFromHeadquarters(contact.Email)) ...
else if (LooksLikeInternalEmail(contact.Email)) ...
Another scenario:
You might have a method like:
public void SaveContact(Contact contact)
if (contact.email != null && contact.email.contains('@'))
contacts.Add(contact);
contacts.Save();
If this fits your business logic and isn't reused there is not a problem here.
But when someone asks "Why is '@' saved, because that's not right!" and you decide to add actual validation of some sort, then extract it!
You'll be glad you did when you also need to account for the presidents second email account Pr3$sid3nt@h0m3!@mydomain.com and decide to just go all out and try and support RFC 2822.
On readability:
// If there is an email property and it contains an @ sign then process
if (contact.email != null && contact.email.contains('@'))
If your code is this clear, you don't need comments here. In fact, you don't need comments to say what the code is doing most the time, but rather why it's doing it:
// The UI passes '@' by default, the DBA's made this column non-nullable but
// marketing is currently more concerned with other fields and '@' default is OK
if (contact.email != null && contact.email.contains('@'))
Whether the comments above an if statement or inside a tiny method is to me, pedantic. I might even argue the opposite of useful with good comments inside another method because now you would have to navigate to another method to see how and why it does what it does.
In summary: Don't measure these things; Focus on the principles that the text was built from (DRY, SOLID, KISS).
// A valid class that does nothing
public class Nothing
answered 4 hours ago
AthomSfereAthomSfere
1617
1617
add a comment |
add a comment |
There's lots of wisdom in the existing answers, but I'd like to add in one more factor: the language.
Some languages take more code than others to get the same effect. In particular, while Java (which I suspect is the language in the question) is extremely well-known and generally very solid and clear and straightforward, some more modern languages are much more concise and expressive.
For example, in Java it could easily take 50 lines to write a new class with three properties, each with a getter and setter, and one or more constructors — while you can accomplish exactly the same in a single line of Kotlin* or Scala. (Even greater saving if you also wanted suitable equals()
, hashCode()
, and toString()
methods.)
The result is that in Java, the extra work means you're more likely to reuse a general object that doesn't really fit, to squeeze properties into existing objects, or to pass a bunch of ‘bare’ properties around individually; while in a concise, expressive language, you're more likely to write better code.
(This highlights the difference between the ‘surface’ complexity of the code, and the complexity of the ideas/models/processing it implements. Lines of code isn't a bad measure of the first, but has much less to do with the second.)
So the ‘cost’ of doing things right depends on the language. Perhaps one sign of a good language is one that doesn't make you choose between doing things well, and doing them simply!
(* This isn't really the place for a plug, but Kotlin is well worth a look IMHO.)
add a comment |
There's lots of wisdom in the existing answers, but I'd like to add in one more factor: the language.
Some languages take more code than others to get the same effect. In particular, while Java (which I suspect is the language in the question) is extremely well-known and generally very solid and clear and straightforward, some more modern languages are much more concise and expressive.
For example, in Java it could easily take 50 lines to write a new class with three properties, each with a getter and setter, and one or more constructors — while you can accomplish exactly the same in a single line of Kotlin* or Scala. (Even greater saving if you also wanted suitable equals()
, hashCode()
, and toString()
methods.)
The result is that in Java, the extra work means you're more likely to reuse a general object that doesn't really fit, to squeeze properties into existing objects, or to pass a bunch of ‘bare’ properties around individually; while in a concise, expressive language, you're more likely to write better code.
(This highlights the difference between the ‘surface’ complexity of the code, and the complexity of the ideas/models/processing it implements. Lines of code isn't a bad measure of the first, but has much less to do with the second.)
So the ‘cost’ of doing things right depends on the language. Perhaps one sign of a good language is one that doesn't make you choose between doing things well, and doing them simply!
(* This isn't really the place for a plug, but Kotlin is well worth a look IMHO.)
add a comment |
There's lots of wisdom in the existing answers, but I'd like to add in one more factor: the language.
Some languages take more code than others to get the same effect. In particular, while Java (which I suspect is the language in the question) is extremely well-known and generally very solid and clear and straightforward, some more modern languages are much more concise and expressive.
For example, in Java it could easily take 50 lines to write a new class with three properties, each with a getter and setter, and one or more constructors — while you can accomplish exactly the same in a single line of Kotlin* or Scala. (Even greater saving if you also wanted suitable equals()
, hashCode()
, and toString()
methods.)
The result is that in Java, the extra work means you're more likely to reuse a general object that doesn't really fit, to squeeze properties into existing objects, or to pass a bunch of ‘bare’ properties around individually; while in a concise, expressive language, you're more likely to write better code.
(This highlights the difference between the ‘surface’ complexity of the code, and the complexity of the ideas/models/processing it implements. Lines of code isn't a bad measure of the first, but has much less to do with the second.)
So the ‘cost’ of doing things right depends on the language. Perhaps one sign of a good language is one that doesn't make you choose between doing things well, and doing them simply!
(* This isn't really the place for a plug, but Kotlin is well worth a look IMHO.)
There's lots of wisdom in the existing answers, but I'd like to add in one more factor: the language.
Some languages take more code than others to get the same effect. In particular, while Java (which I suspect is the language in the question) is extremely well-known and generally very solid and clear and straightforward, some more modern languages are much more concise and expressive.
For example, in Java it could easily take 50 lines to write a new class with three properties, each with a getter and setter, and one or more constructors — while you can accomplish exactly the same in a single line of Kotlin* or Scala. (Even greater saving if you also wanted suitable equals()
, hashCode()
, and toString()
methods.)
The result is that in Java, the extra work means you're more likely to reuse a general object that doesn't really fit, to squeeze properties into existing objects, or to pass a bunch of ‘bare’ properties around individually; while in a concise, expressive language, you're more likely to write better code.
(This highlights the difference between the ‘surface’ complexity of the code, and the complexity of the ideas/models/processing it implements. Lines of code isn't a bad measure of the first, but has much less to do with the second.)
So the ‘cost’ of doing things right depends on the language. Perhaps one sign of a good language is one that doesn't make you choose between doing things well, and doing them simply!
(* This isn't really the place for a plug, but Kotlin is well worth a look IMHO.)
answered 6 hours ago
giddsgidds
1652
1652
add a comment |
add a comment |
Clean Code is an excellent book, and well worth reading, but it is not the final authority on such matters.
Breaking code down into logical functions is usually a good idea, but few programmers do it to the extent that Martin does - at some point you get diminishing returns from turning everything into functions and it can get hard to follow when all the code is in tiny pieces.
One option when it's not worth creating a whole new function is to simply use an intermediate variable:
boolean isEmailValid = (contact.email != null && contact.emails.contains('@');
if (isEmailValid) {
...
This helps keep the code easy to follow without having to jump around the file a lot.
Another issue is that Clean Code is getting quite old as a book now. A lot of software engineering has moved in the direction of functional programming, whereas Martin goes out of his way to add state to things and create objects. I suspect he would have written quite a different book if he'd written it today.
add a comment |
Clean Code is an excellent book, and well worth reading, but it is not the final authority on such matters.
Breaking code down into logical functions is usually a good idea, but few programmers do it to the extent that Martin does - at some point you get diminishing returns from turning everything into functions and it can get hard to follow when all the code is in tiny pieces.
One option when it's not worth creating a whole new function is to simply use an intermediate variable:
boolean isEmailValid = (contact.email != null && contact.emails.contains('@');
if (isEmailValid) {
...
This helps keep the code easy to follow without having to jump around the file a lot.
Another issue is that Clean Code is getting quite old as a book now. A lot of software engineering has moved in the direction of functional programming, whereas Martin goes out of his way to add state to things and create objects. I suspect he would have written quite a different book if he'd written it today.
add a comment |
Clean Code is an excellent book, and well worth reading, but it is not the final authority on such matters.
Breaking code down into logical functions is usually a good idea, but few programmers do it to the extent that Martin does - at some point you get diminishing returns from turning everything into functions and it can get hard to follow when all the code is in tiny pieces.
One option when it's not worth creating a whole new function is to simply use an intermediate variable:
boolean isEmailValid = (contact.email != null && contact.emails.contains('@');
if (isEmailValid) {
...
This helps keep the code easy to follow without having to jump around the file a lot.
Another issue is that Clean Code is getting quite old as a book now. A lot of software engineering has moved in the direction of functional programming, whereas Martin goes out of his way to add state to things and create objects. I suspect he would have written quite a different book if he'd written it today.
Clean Code is an excellent book, and well worth reading, but it is not the final authority on such matters.
Breaking code down into logical functions is usually a good idea, but few programmers do it to the extent that Martin does - at some point you get diminishing returns from turning everything into functions and it can get hard to follow when all the code is in tiny pieces.
One option when it's not worth creating a whole new function is to simply use an intermediate variable:
boolean isEmailValid = (contact.email != null && contact.emails.contains('@');
if (isEmailValid) {
...
This helps keep the code easy to follow without having to jump around the file a lot.
Another issue is that Clean Code is getting quite old as a book now. A lot of software engineering has moved in the direction of functional programming, whereas Martin goes out of his way to add state to things and create objects. I suspect he would have written quite a different book if he'd written it today.
answered 2 hours ago
Rich SmithRich Smith
1834
1834
add a comment |
add a comment |
Let's assume that you are working with class Contact
currently. The fact that you are writing another method for validation of email address is evidence of the fact that the class Contact
is not handling a single responsibility.
It is also handling some email responsibility, which ideally, should be its own class.
Further proof that your code is a fusion of Contact
and Email
class is that you will not be able to test email validation code easily. It will require a lot of maneuverings to reach email validation code in a big method with the right values. See the method viz below.
private void LargeMethod()
//A lot of code which modifies a lot of values. You do all sorts of tricks here.
//Code.
//Code..
//Code...
//Email validation code becoming very difficult to test as it will be difficult to ensure
//that you have the right data till you reach here in the method
ValidateEmail();
//Another whole lot of code that modifies all sorts of values.
//Extra work to preserve the result of ValidateEmail() for your asserts later.
On the other hand, if you had a separate Email class with a method for email validation, then to unit test your validation code you would just make one simple call to Email.Validation()
with your test data.
Bonus Content: MFeather's talk about the deep synergy between testability and good design.
add a comment |
Let's assume that you are working with class Contact
currently. The fact that you are writing another method for validation of email address is evidence of the fact that the class Contact
is not handling a single responsibility.
It is also handling some email responsibility, which ideally, should be its own class.
Further proof that your code is a fusion of Contact
and Email
class is that you will not be able to test email validation code easily. It will require a lot of maneuverings to reach email validation code in a big method with the right values. See the method viz below.
private void LargeMethod()
//A lot of code which modifies a lot of values. You do all sorts of tricks here.
//Code.
//Code..
//Code...
//Email validation code becoming very difficult to test as it will be difficult to ensure
//that you have the right data till you reach here in the method
ValidateEmail();
//Another whole lot of code that modifies all sorts of values.
//Extra work to preserve the result of ValidateEmail() for your asserts later.
On the other hand, if you had a separate Email class with a method for email validation, then to unit test your validation code you would just make one simple call to Email.Validation()
with your test data.
Bonus Content: MFeather's talk about the deep synergy between testability and good design.
add a comment |
Let's assume that you are working with class Contact
currently. The fact that you are writing another method for validation of email address is evidence of the fact that the class Contact
is not handling a single responsibility.
It is also handling some email responsibility, which ideally, should be its own class.
Further proof that your code is a fusion of Contact
and Email
class is that you will not be able to test email validation code easily. It will require a lot of maneuverings to reach email validation code in a big method with the right values. See the method viz below.
private void LargeMethod()
//A lot of code which modifies a lot of values. You do all sorts of tricks here.
//Code.
//Code..
//Code...
//Email validation code becoming very difficult to test as it will be difficult to ensure
//that you have the right data till you reach here in the method
ValidateEmail();
//Another whole lot of code that modifies all sorts of values.
//Extra work to preserve the result of ValidateEmail() for your asserts later.
On the other hand, if you had a separate Email class with a method for email validation, then to unit test your validation code you would just make one simple call to Email.Validation()
with your test data.
Bonus Content: MFeather's talk about the deep synergy between testability and good design.
Let's assume that you are working with class Contact
currently. The fact that you are writing another method for validation of email address is evidence of the fact that the class Contact
is not handling a single responsibility.
It is also handling some email responsibility, which ideally, should be its own class.
Further proof that your code is a fusion of Contact
and Email
class is that you will not be able to test email validation code easily. It will require a lot of maneuverings to reach email validation code in a big method with the right values. See the method viz below.
private void LargeMethod()
//A lot of code which modifies a lot of values. You do all sorts of tricks here.
//Code.
//Code..
//Code...
//Email validation code becoming very difficult to test as it will be difficult to ensure
//that you have the right data till you reach here in the method
ValidateEmail();
//Another whole lot of code that modifies all sorts of values.
//Extra work to preserve the result of ValidateEmail() for your asserts later.
On the other hand, if you had a separate Email class with a method for email validation, then to unit test your validation code you would just make one simple call to Email.Validation()
with your test data.
Bonus Content: MFeather's talk about the deep synergy between testability and good design.
answered 11 hours ago
displayNamedisplayName
1273
1273
add a comment |
add a comment |
CRDev is a new contributor. Be nice, and check out our Code of Conduct.
CRDev is a new contributor. Be nice, and check out our Code of Conduct.
CRDev is a new contributor. Be nice, and check out our Code of Conduct.
CRDev is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Software Engineering Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f388802%2fhow-do-you-justify-more-code-being-written-by-following-clean-code-practices%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
53
If your organization uses only LOC as a metric for your code bases, then justifying clean code there is hopeless to begin with.
– Kilian Foth
15 hours ago
2
It's not the only metric, but it's somewhat important because we are a very small team supporting a relatively large and undocumented code base (that we inherited), so some developers/managers see value in writing less code to get things done so that we have less code to maintain.
– CRDev
15 hours ago
7
If maintainability is your goal, LOC is not the best metric to judge - it's one of them, but there's far more to consider than simply keeping it short.
– Zibbobz
13 hours ago
3
@KilianFoth Given that it's been demonstrated multiple times that every "more worthwhile" metric is strongly correlated with LOC count, an organization could certainly do worse than to adopt "keeping LOC per feature ratio low" as their only metric.
– Mason Wheeler
12 hours ago
5
Is not an answer, but a point to be made: There is a whole subcommunity about writing code with as few lines/symbols as possible. codegolf.stackexchange.com One can argue that most of the answers there are not as readable as they could be.
– Antitheos
12 hours ago