133

Whenever I find myself writing the same logic more than once, I usually stick it in a function so there is only one place in my application I have to maintain that logic. A side effect is that I sometimes end up with one or two line functions such as:

function conditionMet(){
   return x == condition;
}

OR

function runCallback(callback){
   if($.isFunction(callback))
     callback();
}

Is this lazy or a bad practice? I only ask because this results in a greater number of function calls for very tiny pieces of logic.

Mark Brown
  • 603
  • 2
  • 6
  • 7
  • 3
    No, not too short. In C# I would do 'condition met' as a property, which is elegant, and would consider using `Assert.AreEqual(expected, actual, message, arg1, arg2, arg3, ...);`. The second one is fine as is. I would potentially include an optional bool flag which would dictate whether to throw an exception/etc. in case the callback is not a function. – Job Apr 01 '11 at 20:04
  • 39
    Yes, only in one case: function myFunction() {} – Spooks Apr 01 '11 at 20:43
  • 1
    Awesome question. I feel like this all the time. I feel like I have function overload because I have so many 1-3 line functions that only get used once or twice. – Zack Apr 02 '11 at 00:05
  • 6
    `def yes(): return 'yes'` – dietbuddha Apr 02 '11 at 01:03
  • that's exactly why i love Lambdas in C# – Shekhar_Pro Apr 02 '11 at 06:30
  • @Mark, the number of function calls depends on the platform. For modern Java Virtual Machines short functions are inlined in the calling code, avoiding the actual call. –  Apr 02 '11 at 06:46
  • 3
    @Spooks - I'm splitting hairs here but empty functions are valid for at least adapter classes e.g. MouseMotionAdapter in http://download.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html . Of course this only a way to work around language limitations. – Aleksi Yrttiaho Apr 02 '11 at 06:55
  • 1
    @Spooks: Those would be called NOPs. There are actually uses for such functions, though usually not in high-level languages. See: http://en.wikipedia.org/wiki/NOP – Rei Miyasaka Apr 02 '11 at 07:38
  • @dietbuddha `char* no() { return("no"); }` – Mateen Ulhaq Apr 02 '11 at 08:37
  • `int floor(float x) { return(x); }` Of course, this is not necessary if you use type-casting, but it does show the intent better than `(int)x`. – Mateen Ulhaq Apr 02 '11 at 08:41
  • these functions just make your application enterprise :) – KARASZI István Apr 02 '11 at 08:47
  • 3
    @dietbuddha: The requirements just changed - now it has to support two languages for a demo next week. The guy who wrote "def yes()" felt very glad he had before changing it to "def yes( : (IsFrench() ? 'Oui' : 'Yes')" – Andrew Shepherd Apr 06 '11 at 10:57
  • @Andrew Shepard: That's not good programing for i18n/L10n. – dietbuddha Apr 06 '11 at 17:24
  • 1
    I'm currently trying to refactor a codebase with functions several hundreds of lines long... the class I'm in is over 5000 lines (and that was after I separated it from a 14000 line frmMain.cs). I WISH I had this problem :p – KChaloux Aug 14 '12 at 15:26
  • An empty/does-nothing function is also useful for callbacks that don't check for null before calling, like the Null Object pattern for objects. – JBRWilkinson Aug 14 '12 at 20:30
  • @Spooks No, that is common to see in javascript: `function foo(callback) { callback = callback || function () {}; /* do stuff */ callback(); }` – Izkata Feb 08 '13 at 01:45
  • 2
    Possible duplicate of [One-line functions that are called only once](https://softwareengineering.stackexchange.com/questions/107669/one-line-functions-that-are-called-only-once) – gnat Jul 17 '17 at 08:12
  • @Spooks: Actually, there is a perfectly legitimate use case for that function, as an event callback, when the particular event in the particular system does not need any handling at all. (This is not hypothetical. Ca. 1994, I wrote a generalized device driver for a Signetics 2681 DUART (dual UART). Certain things could cause interrupts, which would require service. In our particular project's case, we were not using those interrupts, but the driver still needed a callback for them. The project next door picked up the driver and reported that it dropped right into their system.) – John R. Strohm Jul 17 '17 at 13:43

19 Answers19

170

Hehe, oh Mr Brown, if only I could persuade all the developers I meet to keep their functions as small as this, believe me, the software world would be a better place!

1) Your code readability increases ten fold.

2) So easy to figure out the process of your code because of the readability.

3) DRY - Don't Repeat Yourself - You're conforming to this very well!

4) Testable. Tiny functions are a million times easier to test than those 200 line methods we see way too often.

Oh and don't worry about "function hopping" in terms of performance. "Release" builds and compiler optimisations take care of this for us very nicely, and performance is 99% of the time somewhere else in the systems design.

Is this lazy? - Very much the opposite!

Is this bad practice? - Absolutely not. Better to pulled this way of making methods than the tar balls or "God Objects" that are oh so too common.

Keep up the good work my fellow craftsman ;)

Martin Blore
  • 4,645
  • 5
  • 29
  • 35
  • 43
    You're not answering the question, you're just preaching the rule whose more extreme applications are questioned here. –  Apr 01 '11 at 19:29
  • 3
    Is my answer really hard to tell? Here, I'll make an edit.. – Martin Blore Apr 01 '11 at 19:31
  • 4
    It's not very often that I find the limitation of just 1 upvote frustrating. But, for this answer, +1 doesn't seem to do it justice. – Bevan Apr 01 '11 at 19:52
  • Awesome. Thanks MeshMan. Glad to see there are some solid arguments in favor of my intuition. – Mark Brown Apr 01 '11 at 20:10
  • 3
    Inlining overly small functions is the compiler's job, not yours. Programmers should choose the right algorithm, the compiler should be making the most maintainable implementation of that algorithm efficient. – tobyodavies Apr 02 '11 at 02:05
  • I don't know what the point of testing very small functions is, if the test code is just going to be a one-term inverse expresion of the function itself. Either way only the ones that consume those functions are going to be the ones worth testing. – Rei Miyasaka Apr 02 '11 at 07:59
  • 4
    +5... oh can only do +1, oh well! And to support MeshMan, I suggest the following book by Robert C. Martin [Clean code](http://www.amazon.ca/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882). This book is really changing the way I now program. – Eric-Karl Apr 02 '11 at 16:40
  • +1 Amen. And +1 Eric-Karl. Clean Code goes into depth about this situation. – Steven Evers Apr 02 '11 at 19:01
  • @Eric, @SnOrfus, judging from your comments, you may be interested in the [second-most voted answer](http://programmers.stackexchange.com/questions/64514#64514) to this question... :) – Benjol Apr 06 '11 at 14:03
  • 10
    Very likable answer, but I disagree with most of it: 1) Extremely small functions result in more code overall, because of all the plumbing necessary for each function. This may reduce readability, especially for a really big project. Also, language dependent. 2) Depends entirely on point 1, and therefore has nothing to do with the question. 3) What? runCallback repeats "callback" four times, and three times refers to the same variable to run a single function. 4) 200+ line methods are of course not testable, but there's a long way from that to one line. – l0b0 Jun 09 '11 at 14:04
  • @l0b0 Regarding runCallback, what would be better in your opinion? Specifically in the case where several 'callbacks' may or may not be defined, and you only want to run each of these callbacks if they are actually defined? – Mark Brown Jun 25 '11 at 06:23
  • 12
    -1: The most scarying thing here is the number of up-votes given to this answer. – Luca Jun 06 '12 at 21:39
  • 2
    It **is** lazy. But in software that's usually a good thing. – Zachary Yates Feb 08 '13 at 02:12
  • 1
    @Luca Is there anything else why you gave -1, or is it really only because of up votes? I would really recommend you to read "Clean code" and come back to this answer. – BЈовић Jun 10 '14 at 13:10
  • 1
    @BЈовић The reason of my downvote is explained well by the comments above (especially the l0b0 's one). I commented because surprised by the community criticism too low. The concepts in the answer are good in principle, but applicable only on a small codebase. – Luca Jun 10 '14 at 14:17
66

I would say that a refactored method is too short if either:

  • It duplicates a primitive operation, for no other purpose than to make it a method:

Ex:

boolean isNotValue() {
   return !isValue();
}

or...

  • The code is only used once, and its intent is easy to understand at a glance.

Ex:

void showDialog() {
    Dialog singleUseDialog = new ModalDialog();
    configureDialog(singleUseDialog);
    singleUseDialog.show();
}

void configureDialog(Dialog singleUseDialog) {
    singleUseDialog.setDimensions(400, 300);
}

This could be a valid pattern, but I would just inline the configureDialog() method, in this example, unless I intended to override it or reuse this code elsewhere.

RMorrisey
  • 331
  • 2
  • 4
  • 8
    Separating a single line method in the second case can be beneficial to keep the calling methods abstraction level consistent. The example provided is on the fence if this reasoning is used: is exact pixel width and height too much detail for showing a dialog? – Aleksi Yrttiaho Apr 02 '11 at 05:34
  • 3
    The "isNotValue()" method is badly named and should be refactored to name the actual domain question. –  Apr 02 '11 at 12:34
  • 4
    @Aleksi: I disagree; the details are already hidden within the showDialog() method in this example; there's no need to double-refactor it. The example is intended to show an isolated use case; if a pattern is needed with different dialog configurations in different cases, it would make sense to go back and refactor once the pattern is established. – RMorrisey Apr 04 '11 at 22:30
  • 1
    @Thorbjorn: I could see a case for it, when you're answering a business domain question whose logic might not be obvious. I'm just pointing out that there are -some- cases where it's overkill. – RMorrisey Apr 04 '11 at 22:32
  • 3
    Maybe this is nitpicking, but i would argue that in your examples the problem is not that the function is too short, but that they do not add descriptive value. – keppla Jun 09 '11 at 15:12
  • @keppla: That's quite right. But i think shortness can sometimes contribute to a lack of descriptiveness; if a method doesn't do much, there isn't much to say about it. – Tom Anderson Jun 09 '11 at 15:25
  • I agree with keppla. I frequently use single-line functions as a wrapper to tie a specific use case to an abstract API call. For example, I'll put a single line of math inside a function that's named for what that formula is used to calculate. – jhocking Jun 09 '11 at 16:44
  • @tom: i agree that with short functions, there is a higher probability that there is an already existing equivalent with the same descriptive power (as in your !isValue example). But, in my opinion, a function like `function empty() { return this.length == 0 }` is good, even it is syntactial like your isNoValue example (both are just aliases for a simple calculation with one operator) – keppla Jun 09 '11 at 21:52
59

Can a function be too short? In general no.

In fact the only way to ensure that:

  1. You have found all the classes in your design
  2. Your functions are doing only one thing.

Is to keep your functions as small as possible. Or, in other words, extract functions from your functions until you can't extract any more. I call this "Extract till you drop."

To explain this: A function is a scope with chunks of functionality that communicate by variables. A class is also a scope with chunks of functionality that communicate by variables. So a long function can always be replaced by one or more classes with small method.

Also, a function that is big enough to allow you to extract another function from it, is doing more than one thing by definition. So if you can extract a function from another, you should extract that function.

Some folks worry that this will lead to a proliferation of functions. They're right. It will. That's actually a good thing. It's good because functions have names. If you are careful about choosing good names, then these functions act as sign posts that direct other people through your code. Indeed, well named functions inside of well named classes inside of well named namespaces are one of the best ways to make sure that your readers do NOT get lost.

There's a lot more about this in Episode III of Clean Code at cleancoders.com

Uncle Bob.
  • 3,565
  • 2
  • 17
  • 10
  • 5
    Uncle Bob! Great to see you on board here. As expected, fantastic advice. I've never heard the term "Extract till you drop" before and will certainty be using this term around the office on Monday ;). – Martin Blore Apr 02 '11 at 00:40
  • 1
    Would you be willing to elaborate on your point #1? Explaining that by example would be great. – Daniel Kaplan Feb 07 '13 at 23:11
53

Wow, most of these answers aren't very helpful at all.

No function should be written whose identity is its definition. That is, if the function name is simply the function's code block written out in English, then don't write it as a function.

Consider your function conditionMet and this other function, addOne (forgive me for my rusty JavaScript):

function conditionMet() { return x == condition; }

function addOne(x) { return x + 1; }

conditionMet is a proper conceptual definition; addOne is a tautology. conditionMet is good because you don't know what conditionMet entails just by saying "condition met", but you can see why addOne is silly if you read it out in English:

"For the condition to be met is for x to equal condition" <-- explanatory! meaningful! useful!

"To add one to x is to take x and add one." <-- wtf!

For the love of anything that might still be holy, please, don't write tautological functions!

(And for the same reason, don't write comments for every line of code!)

Rei Miyasaka
  • 4,541
  • 1
  • 32
  • 36
  • Some of the more complex language constructs may be unfamiliar or hard to read, making this a useful trick. –  Apr 02 '11 at 12:37
  • 3
    Agreed, what exactly should be made into a function would depend largely on the language it's being written in. A function like addOne would be useful if you were in a language like VHDL, where you're actually defining the meaning of adding one on a binary or number theory level. I'd like to think that no language out there is so cryptic that it's hard to read even for practiced programmers (maybe brainf#ck), but if that's the case, the same idea would stand since the function is effectively a translation from English to that language -- so the name isn't the same as the definition. – Rei Miyasaka Apr 02 '11 at 21:03
  • Tautological functions are fine for higher order code (although in this case you often use anonymous lambdas instead) – hugomg Nov 11 '11 at 11:54
  • @missingno Can you give me an example? – Rei Miyasaka Nov 12 '11 at 02:50
  • 1
    I'm talking about things [identity function](http://stackoverflow.com/questions/3136338/uses-for-haskell-id-function) from the Haskell standard library - I don't think you can get more "tautological" then that :) – hugomg Nov 12 '11 at 03:22
  • 1
    @missingno Bah, that's cheating :D – Rei Miyasaka Nov 12 '11 at 04:13
  • Though I'm not entirely sure I'm convinced that an identity and a tautology are the same thing... hmm... even if they were, I'd argue that `id` is exceptional in that it's an extremely terse shorthand for `\x -> x`. – Rei Miyasaka Nov 12 '11 at 04:13
  • 5
    If you name the functions by their purpose instead of by their content, they immediately stop being silly. So your examples might be e.g. be `function nametoolong() { return name.size > 15; }` or `function successorIndex(x) { return x + 1; }` So the problem with your functions is actually just that they their name is bad. – Dr. Hans-Peter Störr Jan 02 '12 at 19:06
  • I would slightly differ: it's entirely proper to write a function whose name is synonymous with its action, if there will be cases when it's appropriate to use it. Such usage is appropriate in cases where e.g. the function will be converted to a delegate, or where an RValue is required but the thing to be done won't "fit" in an RValue [e.g. a constructor needs to perform an action before chaining to a parent constructor]. – supercat Jul 15 '14 at 17:42
15

I'd say that if you think the intention of some code can be improved by adding a comment, then rather than adding that comment, extract the code into its own method. No matter how small the code was.

So for example if your code was going to look like:

if x == 1 { ... } // is pixel on?

make it look like this instead:

if pixelOn() { ... }

with

function pixelOn() { return x == 1; }

Or in other words, it's not about the method length, but about self-documenting code.

Julio
  • 1,854
  • 13
  • 10
  • 6
    My esteemed colleague points out that you could also write `if x == PIXEL_ON`. Using a constant can be as descriptive as using a method, and is a little briefer. – Tom Anderson Jun 09 '11 at 15:28
7

I think this is exactly what you want to do. Right now that function might only be one or two lines but over time it could grow. Also having more function calls allows you to read the function calls and understand what is happening inside there. This makes your code very DRY (Don't Repeat Yourself) which is much more maintainable.

mpenrow
  • 1,653
  • 13
  • 16
  • 4
    So what's wrong with factoring it out later, when you can prove you need to, instead of now, when it's just dead weight? – dsimcha Apr 02 '11 at 20:03
  • Functions don't grow on their own. IMHO the examples are lousy. `conditionMet` is a too generic name, and takes no argument, so it tests some state? (x == xCondition) is in most languages and situations as expressive as 'xConditition'. – user unknown Jun 09 '11 at 01:11
  • Yes, and that's why you want to have 75%+ overhead in your code? Singe liner written as 3 lines is actually 300%. – Coder Jun 09 '11 at 13:28
5

I agree with all the other posts I have seen. This is good style.

The overhead of such a small method may be nil as the optimizer may optimize the the call away and inline the code. Simple code like this is allows the optimizer to do its best work.

Code should be written for clarity and simplicity. I try to limit a method to one of two roles: making decisions; or performing work. This may generate one line methods. The better I am at doing this, the better I find my code is.

Code like this tends to have high cohesion and low coupling which is good coding practice.

EDIT: A note on method names. Use a method name which indicates what the method does not how it does it. I find verb_noun(_modifier) is a good naming scheme. This give names like Find_Customer_ByName rather than Select_Customer_Using_NameIdx. The second case is prone to become incorrect when the method is modified. In the first case, you can swap out the entire Customer database implementation.

BillThor
  • 6,232
  • 17
  • 17
4

Refactoring one line of code into a function seems excessive. There might be exceptional cases, such as ver loooooong/comples lines or expessions, but I wouldn't do this unless I know the function will grow in the future.

and your first example hints at use of globals (which may or may not speak of other issues in the code), I'd refactor it further, and make those two variables as parameters:

function conditionMet(x, condition){
   return x == condition;
}
....
conditionMet(1,(3-2));
conditionMet("abc","abc");

The conditionMet example might be useful if the condition was long and repetitive such as:

function conditionMet(x, someObject){
   return x == ((someObject.valA + someObject.valB - 15.4) / /*...whole bunch of other stuff...*/);
}
FrustratedWithFormsDesigner
  • 46,105
  • 7
  • 126
  • 176
  • 1
    His first example does not hint of globals. If anything, it's a cohesive method in a highly cohesive class where most of the variables are on the object. – Martin Blore Apr 01 '11 at 19:34
  • 7
    That `conditionMet` function is just a verbose `==` operator. That's propably not useful. –  Apr 01 '11 at 19:34
  • 1
    I definitely don't use globals. @MeshMan, thats exactly where the example is from...a method on a class. – Mark Brown Apr 01 '11 at 19:36
  • 1
    @Mark Brown: @MeshMan: Ok, I guess the code example was too vague to know for sure... – FrustratedWithFormsDesigner Apr 01 '11 at 19:40
  • I'm smelling a `conditionMet (x, relation condition) {` here, where you pass x, '==' and relation. Then you needn't repeat the code for '<', '>', '<=', '!=' and so on. On the other side - most languages have these constructs build in as operators (x == condition) does just that. Functions for atomic statements is one step too far. – user unknown Jun 09 '11 at 01:18
3

Consider this:

A simple collision detection function:

bool collide(OBJ a, OBJ b)
{
    return(pow(a.x - b.x, 2) + pow(a.y - b.y, 2) <= pow(a.radius + b.radius, 2));
}

If you wrote that "simple" one liner in your code all the time, you might eventually make a mistake. Plus, it'd be really torturous to write that over and over.

Mateen Ulhaq
  • 968
  • 3
  • 11
  • 21
  • If we're dealing with C here, we could just abuse `#define` ;) – Cole Tobin May 09 '14 at 00:07
  • You might even want to swap this out for the slower but overflow-proof [hypot](http://en.wikipedia.org/wiki/Hypot) if your sizes or distances become very large. This is, obviously, a lot easier to do once. – Matt Krause May 09 '14 at 03:58
2

No, and that is rarely a problem. Now if someone feels no function should be longer than one line of code (if only it could be that simple), that would be a problem and in some ways lazy because they are not thinking about what is appropriate.

JeffO
  • 36,816
  • 2
  • 57
  • 124
  • I wouldn't count it in lines of code, but in expressions. "(x == condition)" is atomic, so I would put it into a method/function only, if it is used multiple times AND might be changed, like `function isAdult () = { age >= 18; }` but surely not `isAtLeast18`. – user unknown Jun 09 '11 at 01:20
2

I would say they are too short, but this is my subjective opinion.

Because:

  • There is no reason to create a function if it's used only once or twice. Jumping to defs suck. Especially with amazingly fast VS and C++ code.
  • Class overview. When you have thousands of small functions, it drives me angry. I enjoy when I can view class definitions and quickly see what it does, not how it SetXToOne, SetYToVector3, MultiplyNumbers, + 100 setters/getters.
  • In most projects these helpers become dead weight after one ore two refactoring phases, and then you do "search all"->delete to get rid of obsolete code, usually ~25%+ of it.

Functions that are long are bad, but functions that are shorter than 3 lines and perform only 1 thing are equally bad IMHO.

So I'd say only write small function if it's:

  • 3+ lines of code
  • Does stuff that junior devs might miss (not know)
  • Does extra validation
  • Is used, or will used at least 3x
  • Simplifies frequently used interface
  • Will not become a dead weight during next refactoring
  • Has some special meaning, for example, template specialization or something
  • Does some isolation job - const references, affects mutable parameters, does private member retrieval

I bet next developer (senior) will have better things to do than to remember all your SetXToOne functions. So they'll turn into dead weight pretty soon either way.

Coder
  • 6,958
  • 5
  • 37
  • 49
1

I don't like the example no. 1, bcause of ith generic name.

conditionMet does not seem to be generic, so it stands for a specific condition? Like

isAdult () = { 
  age >= 18 
}

This would be fine. It's a semantic difference, while

isAtLeast18 () { age >= 18; } 

would not be fine for me.

Maybe it is often used, and can be subject for later change:

getPreferredIcecream () { return List ("banana", "choclate", "vanilla", "walnut") }

is fine too. Using it multiple times, you just need to change a single place, if you have to - maybe whipped cream gets possible tomorrow.

isXYZ (Foo foo) { foo.x > 15 && foo.y < foo.x * 2 }

is not atomic, and should give you a nice test opportunity.

If you need to pass a function, of course, pass whatever you like, and write otherwise silly looking functions.

But in general, I see much more functions, which are too long, than functions which are too short.

A last word: Some functions only look appropriate, because they're written too verbose:

function lessThan (a, b) {
  if (a < b) return true else return false; 
}

If you see, that it is the same as

return (a < b); 

you won't have a problem with

localLessThan = (a < b); 

instead of

localLessThan = lessThan (a, b); 
user unknown
  • 797
  • 7
  • 14
0

Too short never is a problem. Some reasons for short functions are:

Reusability

E.g. if you have a function, like a set method, you might assert it to be sure the parameters are valid. This checking has to be done everywhere the variable is set.

Maintainability

You might use some statement that you think in the future may change. E.g. you now show a symbol in a column, but later that might change to something else (or even a beep).

Uniformity

You are using e.g. the facade pattern and the only thing a function does is exactly passing the function to another without changing arguments.

Michel Keijzers
  • 327
  • 2
  • 16
0

When you give a code section a name, it is essentially for giving it a name. This can be for any of several reasons, but the crucial point is if you can give it a meaningful name which adds to your program. Names like "addOneToCounter" would not add anything, but conditionMet() would.

If you need a rule for finding out if the snippet is too short or too long, then consider how long time it takes you to find a meaningful name for the snippet. If you cannot within a reasonable amount of time, then the snippet is not a suitable size.

0

No, but it can be too terse.

Remember: Code is written once, but read many times.

Don't write code for the compiler. Write it for future developers who will have to maintain your code.

Jim G.
  • 8,006
  • 3
  • 35
  • 66
0

There's no code like no code!

Keep it simple and don't over complicate things.

It's not being lazy, it's doing your job!

RDL
  • 1,069
  • 7
  • 10
0

Yes, its ok to have a short code function. In case of methods as "getters", "setters", "accesors" is very common, as previous answers mentioned.

Sometimes, those short "accesors" functions are virtual, because when overriden in subclasses the functions will have more code.

If you want you function not so short, well, in many functions, wheter global or methods, I usually use a "result" variable (pascal style) instead of a direct return, its very helpful when using a debugger.

function int CalculateSomething() {
  int Result = -1;

   // more code, maybe, maybe not

  return Result;
}
umlcat
  • 2,146
  • 11
  • 16
-1

Yes dear, Function could be smaller and smaller and whether it is good or bad it depends on the Language/Framework you're using.

In my opinion I mostly work on Front End Technologies, Small Functions are mostly used as helper functions you'll be bound to use them like a lot when working with small filters and using same logic across your application. If your application has too much common logic then there are gonna be like a ton of small functions.

But in an application where you don't have common logic you won't be bound to make small functions but you can break your code into segments where it becomes easy for you to manage and understand.

In general break your huge code into small function is a very good approach. In modern frameworks and languages you'll be bound to do so e.g

data => initScroll(data)

is an anonymous function in ES 2017 JavaScript and Typescript

getMarketSegments() {
 this.marketService.getAllSegments(this.project.id)
  .subscribe(data => this.segments = data, error => console.log(error.toString()));
}

in the above code you can see 3 Function declaration and 2 function calls this is a simple Service Call in Angular 4 with Typescript. You can think of it as your requirements

([] 0)
([x] 1)
([x y] 2)

The above are 3 Anonymous functions in clojure Language

(def hello (fn [] "Hello world"))

The above one is a functional declaration in clojure

So yes FUNCTIONS can be as smaller but whether it is good or bad if you have functions like:

incrementNumber(numb) { return ++numb; }

Well it is not a good practice to do so but what if you're using this function in an HTML tag like we do in Angular Framework if there was no support for Increment or Decrement in Angular HTML Templates then this would have been the solution for me.

Lets take another example

insertInArray(array, newKey) {
 if (!array.includes(newKey)) {
   array.push(newKey);
 }
}

The above example is a must when playing when arrays inside Angular HTML Templates. So sometimes you'll have to create small functions

-2

I disagree with almost answer given at this time.

Recently I found a colleague which write all classes members like the following:

 void setProperty(int value){ mValue=value; }
 int getProperty() const { return (mValue); }

This could be a good code in sporadic cases, but surely not if you define many classes having many and many properties. I don't want to say, with this, that methods like the ones above shall not be written. But, if you ends up to write most of the code as "wrapper" of the real logic, there is something wrong.

Probably the programmer miss the overall logic, fear about future changes and about refactoring the code.

The definition of the interface is because a real need; indeed if you need to set and get a simple property (without much logic, which makes the member shorter) it shall be possible. But, if the real need could be analysed in a different way, why don't define a more intuitive interface?

To really answer to the question, of course it is no, and the reason is very obvious: the method/property/whatelse shall be defined for what it needs. Even an empty virtual function has a reason to exists.

Luca
  • 294
  • 1
  • 9
  • 6
    There is a good reason to add accessor/mutator methods, which you hint at under "fear about future ... refactoring". But you're also right that it doesn't add value to the code. Neither by reducing size (locally or globally) or increasing readability. In my mind, this speaks to poor language design in both Java and the JavaBeans convention. This is one area (of many) where C# successfully improved the language to address both concerns with the [automatic property syntax](http://tinyurl.com/ysh5mf). As a Java programmer, I agree with your _raw_ style for basic struct-like classes. – Anm Apr 01 '11 at 22:52
  • 1
    Getter/setter functions are good even if all they do right now is read or write a variable. As a practical matter, you can imagine a scenario where later on you decide to print a value to the screen every time the field changes, or to check whether that value is valid or not. (Maybe it's a denominator for a fraction, and you want to check to make sure it's not zero.) – Rei Miyasaka Apr 02 '11 at 07:33
  • 2
    getters and setters are awful, their valid use notwithstanding. If it's necessary to use them, I consider it a failure of the language. – Carson Myers Apr 03 '11 at 07:25
  • @Rei: why would an external class need to check for the value of the denominators? That should be done by the divide() function of the Fraction class or the Fraction class should provide an isDivisible() to check for null denominators. Needing getters/setters are usually a code smell that your class has high coupling and/or low cohesion (i.e. bad). – Lie Ryan Jun 05 '11 at 19:38
  • @Lie What? I never said an external class should be used to check denominators. I'm saying that an external class might set a denominator to 0 by accident. The purpose of having validity checks happen at the setters is to encourage any bugs in consumer code to be found earlier. Providing an isDivisible() function that might or might not be called also doesn't work to that end. And how exactly does needing getters/setters indicate that there's high coupling? – Rei Miyasaka Jun 06 '11 at 01:54