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

When did hardware antialiasing start being available?

Homology of the fiber

How are passwords stolen from companies if they only store hashes?

Why is this tree refusing to shed its dead leaves?

Is there any common country to visit for uk and schengen visa?

Would it be believable to defy demographics in a story?

How to test the sharpness of a knife?

Do I need an EFI partition for each 18.04 ubuntu I have on my HD?

Why doesn't the fusion process of the sun speed up?

Should I be concerned about student access to a test bank?

Friend wants my recommendation but I don't want to

What will the french man say?

Do I need to convey a moral for each of my blog post?

How can I create URL shortcuts/redirects for task/diff IDs in Phabricator?

Does fire aspect on a sword, destroy mob drops?

How to remove space in section title at KOMA-Script

What (if any) is the reason to buy in small local stores?

Error in master's thesis, I do not know what to do

Does the Shadow Magic sorcerer's Eyes of the Dark feature work on all Darkness spells or just his/her own?

What is the difference between something being completely legal and being completely decriminalized?

Would this string work as string?

Why is indicated airspeed rather than ground speed used during the takeoff roll?

Why do I have a large white artefact on the rendered image?

Do people actually use the word "kaputt" in conversation?



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













49















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.










share|improve this question









New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 48





    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
    11 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
    11 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
    9 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
    9 hours ago







  • 4





    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
    8 hours ago















49















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.










share|improve this question









New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 48





    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
    11 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
    11 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
    9 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
    9 hours ago







  • 4





    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
    8 hours ago













49












49








49


5






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.










share|improve this question









New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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






share|improve this question









New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 7 hours ago







CRDev













New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 11 hours ago









CRDevCRDev

30327




30327




New contributor




CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






CRDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 48





    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
    11 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
    11 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
    9 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
    9 hours ago







  • 4





    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
    8 hours ago












  • 48





    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
    11 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
    11 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
    9 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
    9 hours ago







  • 4





    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
    8 hours ago







48




48





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
11 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
11 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
11 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
11 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
9 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
9 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
9 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
9 hours ago





4




4





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
8 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
8 hours ago










9 Answers
9






active

oldest

votes


















42















... 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.






share|improve this answer


















  • 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
    11 hours ago






  • 21





    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
    10 hours ago






  • 7





    @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
    10 hours ago






  • 10





    @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
    10 hours ago






  • 5





    @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
    9 hours ago


















87














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.






share|improve this answer


















  • 9





    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
    7 hours ago


















14














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!






share|improve this answer























  • 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
    9 hours ago






  • 8





    @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
    8 hours ago











  • Progress monitoring is a tough job, isn't it? Poor managers.

    – jos
    8 hours ago


















9















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.






share|improve this answer
































    3














    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.






    share|improve this answer






























      2














      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.






      share|improve this answer
































        1














        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.)






        share|improve this answer






























          1














          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:



          1. 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?

          2. 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.

          3. 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








          share|improve this answer






























            0














            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.






            share|improve this answer























            • @Downvoter: What’s up?

              – displayName
              7 hours ago










            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.









            draft saved

            draft discarded


















            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();


            );
            );






            9 Answers
            9






            active

            oldest

            votes








            9 Answers
            9






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            42















            ... 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.






            share|improve this answer


















            • 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
              11 hours ago






            • 21





              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
              10 hours ago






            • 7





              @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
              10 hours ago






            • 10





              @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
              10 hours ago






            • 5





              @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
              9 hours ago















            42















            ... 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.






            share|improve this answer


















            • 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
              11 hours ago






            • 21





              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
              10 hours ago






            • 7





              @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
              10 hours ago






            • 10





              @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
              10 hours ago






            • 5





              @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
              9 hours ago













            42












            42








            42








            ... 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.






            share|improve this answer














            ... 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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 11 hours ago









            David ArnoDavid Arno

            27.9k65591




            27.9k65591







            • 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
              11 hours ago






            • 21





              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
              10 hours ago






            • 7





              @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
              10 hours ago






            • 10





              @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
              10 hours ago






            • 5





              @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
              9 hours ago












            • 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
              11 hours ago






            • 21





              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
              10 hours ago






            • 7





              @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
              10 hours ago






            • 10





              @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
              10 hours ago






            • 5





              @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
              9 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
            11 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
            11 hours ago




            21




            21





            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
            10 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
            10 hours ago




            7




            7





            @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
            10 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
            10 hours ago




            10




            10





            @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
            10 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
            10 hours ago




            5




            5





            @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
            9 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
            9 hours ago













            87














            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.






            share|improve this answer


















            • 9





              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
              7 hours ago















            87














            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.






            share|improve this answer


















            • 9





              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
              7 hours ago













            87












            87








            87







            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.






            share|improve this answer













            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 11 hours ago









            Karl BielefeldtKarl Bielefeldt

            120k30214412




            120k30214412







            • 9





              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
              7 hours ago












            • 9





              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
              7 hours ago







            9




            9





            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
            7 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
            7 hours ago











            14














            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!






            share|improve this answer























            • 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
              9 hours ago






            • 8





              @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
              8 hours ago











            • Progress monitoring is a tough job, isn't it? Poor managers.

              – jos
              8 hours ago















            14














            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!






            share|improve this answer























            • 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
              9 hours ago






            • 8





              @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
              8 hours ago











            • Progress monitoring is a tough job, isn't it? Poor managers.

              – jos
              8 hours ago













            14












            14








            14







            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!






            share|improve this answer













            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!







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 11 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
              9 hours ago






            • 8





              @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
              8 hours ago











            • Progress monitoring is a tough job, isn't it? Poor managers.

              – jos
              8 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
              9 hours ago






            • 8





              @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
              8 hours ago











            • Progress monitoring is a tough job, isn't it? Poor managers.

              – jos
              8 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
            9 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
            9 hours ago




            8




            8





            @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
            8 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
            8 hours ago













            Progress monitoring is a tough job, isn't it? Poor managers.

            – jos
            8 hours ago





            Progress monitoring is a tough job, isn't it? Poor managers.

            – jos
            8 hours ago











            9















            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.






            share|improve this answer





























              9















              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.






              share|improve this answer



























                9












                9








                9








                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.






                share|improve this answer
















                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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 8 hours ago

























                answered 8 hours ago









                FlaterFlater

                8,65331524




                8,65331524





















                    3














                    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.






                    share|improve this answer



























                      3














                      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.






                      share|improve this answer

























                        3












                        3








                        3







                        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.






                        share|improve this answer













                        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.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered 8 hours ago









                        Clement CherlinClement Cherlin

                        1,175710




                        1,175710





















                            2














                            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.






                            share|improve this answer





























                              2














                              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.






                              share|improve this answer



























                                2












                                2








                                2







                                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.






                                share|improve this answer















                                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.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 7 hours ago

























                                answered 7 hours ago









                                BaldrickkBaldrickk

                                546310




                                546310





















                                    1














                                    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.)






                                    share|improve this answer



























                                      1














                                      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.)






                                      share|improve this answer

























                                        1












                                        1








                                        1







                                        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.)






                                        share|improve this answer













                                        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.)







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered 2 hours ago









                                        giddsgidds

                                        1652




                                        1652





















                                            1














                                            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:



                                            1. 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?

                                            2. 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.

                                            3. 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








                                            share|improve this answer



























                                              1














                                              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:



                                              1. 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?

                                              2. 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.

                                              3. 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








                                              share|improve this answer

























                                                1












                                                1








                                                1







                                                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:



                                                1. 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?

                                                2. 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.

                                                3. 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








                                                share|improve this answer













                                                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:



                                                1. 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?

                                                2. 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.

                                                3. 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









                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered 59 mins ago









                                                AthomSfereAthomSfere

                                                1517




                                                1517





















                                                    0














                                                    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.






                                                    share|improve this answer























                                                    • @Downvoter: What’s up?

                                                      – displayName
                                                      7 hours ago















                                                    0














                                                    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.






                                                    share|improve this answer























                                                    • @Downvoter: What’s up?

                                                      – displayName
                                                      7 hours ago













                                                    0












                                                    0








                                                    0







                                                    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.






                                                    share|improve this answer













                                                    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.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered 8 hours ago









                                                    displayNamedisplayName

                                                    1273




                                                    1273












                                                    • @Downvoter: What’s up?

                                                      – displayName
                                                      7 hours ago

















                                                    • @Downvoter: What’s up?

                                                      – displayName
                                                      7 hours ago
















                                                    @Downvoter: What’s up?

                                                    – displayName
                                                    7 hours ago





                                                    @Downvoter: What’s up?

                                                    – displayName
                                                    7 hours ago










                                                    CRDev is a new contributor. Be nice, and check out our Code of Conduct.









                                                    draft saved

                                                    draft discarded


















                                                    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.




                                                    draft saved


                                                    draft discarded














                                                    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





















































                                                    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











                                                    Popular posts from this blog

                                                    Àrd-bhaile Cathair chruinne/Baile mòr cruinne | Artagailean ceangailte | Clàr-taice na seòladaireachd

                                                    대한민국 목차 국명 지리 역사 정치 국방 경제 사회 문화 국제 순위 관련 항목 각주 외부 링크 둘러보기 메뉴북위 37° 34′ 08″ 동경 126° 58′ 36″ / 북위 37.568889° 동경 126.976667°  / 37.568889; 126.976667ehThe Korean Repository문단을 편집문단을 편집추가해Clarkson PLC 사Report for Selected Countries and Subjects-Korea“Human Development Index and its components: P.198”“http://www.law.go.kr/%EB%B2%95%EB%A0%B9/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%EA%B5%AD%EA%B8%B0%EB%B2%95”"한국은 국제법상 한반도 유일 합법정부 아니다" - 오마이뉴스 모바일Report for Selected Countries and Subjects: South Korea격동의 역사와 함께한 조선일보 90년 : 조선일보 인수해 혁신시킨 신석우, 임시정부 때는 '대한민국' 국호(國號) 정해《우리가 몰랐던 우리 역사: 나라 이름의 비밀을 찾아가는 역사 여행》“남북 공식호칭 ‘남한’‘북한’으로 쓴다”“Corea 대 Korea, 누가 이긴 거야?”국내기후자료 - 한국[김대중 前 대통령 서거] 과감한 구조개혁 'DJ노믹스'로 최단기간 환란극복 :: 네이버 뉴스“이라크 "韓-쿠르드 유전개발 MOU 승인 안해"(종합)”“해외 우리국민 추방사례 43%가 일본”차기전차 K2'흑표'의 세계 최고 전력 분석, 쿠키뉴스 엄기영, 2007-03-02두산인프라, 헬기잡는 장갑차 'K21'...내년부터 공급, 고뉴스 이대준, 2008-10-30과거 내용 찾기mk 뉴스 - 구매력 기준으로 보면 한국 1인당 소득 3만弗과거 내용 찾기"The N-11: More Than an Acronym"Archived조선일보 최우석, 2008-11-01Global 500 2008: Countries - South Korea“몇년째 '시한폭탄'... 가계부채, 올해는 터질까”가구당 부채 5000만원 처음 넘어서“‘빚’으로 내몰리는 사회.. 위기의 가계대출”“[경제365] 공공부문 부채 급증…800조 육박”“"소득 양극화 다소 완화...불평등은 여전"”“공정사회·공생발전 한참 멀었네”iSuppli,08年2QのDRAMシェア・ランキングを発表(08/8/11)South Korea dominates shipbuilding industry | Stock Market News & Stocks to Watch from StraightStocks한국 자동차 생산, 3년 연속 세계 5위자동차수출 '현대-삼성 웃고 기아-대우-쌍용은 울고' 과거 내용 찾기동반성장위 창립 1주년 맞아Archived"중기적합 3개업종 합의 무시한 채 선정"李대통령, 사업 무분별 확장 소상공인 생계 위협 질타삼성-LG, 서민업종인 빵·분식사업 잇따라 철수상생은 뒷전…SSM ‘몸집 불리기’ 혈안Archived“경부고속도에 '아시안하이웨이' 표지판”'철의 실크로드' 앞서 '말(言)의 실크로드'부터, 프레시안 정창현, 2008-10-01“'서울 지하철은 안전한가?'”“서울시 “올해 안에 모든 지하철역 스크린도어 설치””“부산지하철 1,2호선 승강장 안전펜스 설치 완료”“전교조, 정부 노조 통계서 처음 빠져”“[Weekly BIZ] 도요타 '제로 이사회'가 리콜 사태 불러들였다”“S Korea slams high tuition costs”““정치가 여론 양극화 부채질… 합리주의 절실””“〈"`촛불집회'는 민주주의의 질적 변화 상징"〉”““촛불집회가 민주주의 왜곡 초래””“국민 65%, "한국 노사관계 대립적"”“한국 국가경쟁력 27위‥노사관계 '꼴찌'”“제대로 형성되지 않은 대한민국 이념지형”“[신년기획-갈등의 시대] 갈등지수 OECD 4위…사회적 손실 GDP 27% 무려 300조”“2012 총선-대선의 키워드는 '국민과 소통'”“한국 삶의 질 27위, 2000년과 2008년 연속 하위권 머물러”“[해피 코리아] 행복점수 68점…해외 평가선 '낙제점'”“한국 어린이·청소년 행복지수 3년 연속 OECD ‘꼴찌’”“한국 이혼율 OECD중 8위”“[통계청] 한국 이혼율 OECD 4위”“오피니언 [이렇게 생각한다] `부부의 날` 에 돌아본 이혼율 1위 한국”“Suicide Rates by Country, Global Health Observatory Data Repository.”“1. 또 다른 차별”“오피니언 [편집자에게] '왕따'와 '패거리 정치' 심리는 닮은꼴”“[미래한국리포트] 무한경쟁에 빠진 대한민국”“대학생 98% "외모가 경쟁력이라는 말 동의"”“특급호텔 웨딩·200만원대 유모차… "남보다 더…" 호화病, 고질병 됐다”“[스트레스 공화국] ① 경쟁사회, 스트레스 쌓인다”““매일 30여명 자살 한국, 의사보다 무속인에…””“"자살 부르는 '우울증', 환자 중 85% 치료 안 받아"”“정신병원을 가다”“대한민국도 ‘묻지마 범죄’,안전지대 아니다”“유엔 "학생 '성적 지향'에 따른 차별 금지하라"”“유엔아동권리위원회 보고서 및 번역본 원문”“고졸 성공스토리 담은 '제빵왕 김탁구' 드라마 나온다”“‘빛 좋은 개살구’ 고졸 취업…실습 대신 착취”원본 문서“정신건강, 사회적 편견부터 고쳐드립니다”‘소통’과 ‘행복’에 목 마른 사회가 잠들어 있던 ‘심리학’ 깨웠다“[포토] 사유리-곽금주 교수의 유쾌한 심리상담”“"올해 한국인 평균 영화관람횟수 세계 1위"(종합)”“[게임연중기획] 게임은 문화다-여가활동 1순위 게임”“영화속 ‘영어 지상주의’ …“왠지 씁쓸한데””“2월 `신문 부수 인증기관` 지정..방송법 후속작업”“무료신문 성장동력 ‘차별성’과 ‘갈등해소’”대한민국 국회 법률지식정보시스템"Pew Research Center's Religion & Public Life Project: South Korea"“amp;vwcd=MT_ZTITLE&path=인구·가구%20>%20인구총조사%20>%20인구부문%20>%20 총조사인구(2005)%20>%20전수부문&oper_YN=Y&item=&keyword=종교별%20인구& amp;lang_mode=kor&list_id= 2005년 통계청 인구 총조사”원본 문서“한국인이 좋아하는 취미와 운동 (2004-2009)”“한국인이 좋아하는 취미와 운동 (2004-2014)”Archived“한국, `부분적 언론자유국' 강등〈프리덤하우스〉”“국경없는기자회 "한국, 인터넷감시 대상국"”“한국, 조선산업 1위 유지(S. Korea Stays Top Shipbuilding Nation) RZD-Partner Portal”원본 문서“한국, 4년 만에 ‘선박건조 1위’”“옛 마산시,인터넷속도 세계 1위”“"한국 초고속 인터넷망 세계1위"”“인터넷·휴대폰 요금, 외국보다 훨씬 비싸”“한국 관세행정 6년 연속 세계 '1위'”“한국 교통사고 사망자 수 OECD 회원국 중 2위”“결핵 후진국' 한국, 환자가 급증한 이유는”“수술은 신중해야… 자칫하면 생명 위협”대한민국분류대한민국의 지도대한민국 정부대표 다국어포털대한민국 전자정부대한민국 국회한국방송공사about korea and information korea브리태니커 백과사전(한국편)론리플래닛의 정보(한국편)CIA의 세계 정보(한국편)마리암 부디아 (Mariam Budia),『한국: 하늘이 내린 한 폭의 그림』, 서울: 트랜스라틴 19호 (2012년 3월)대한민국ehehehehehehehehehehehehehehWorldCat132441370n791268020000 0001 2308 81034078029-6026373548cb11863345f(데이터)00573706ge128495

                                                    Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition