DEV Community

Discussion on: When do you create a function or method?

Collapse
 
tux0r profile image
tux0r

Whenever I need to reuse code.

Collapse
 
codevault profile image
Sergiu Mureşan

Even when the function is a one liner?

Collapse
 
tux0r profile image
tux0r

Yes.

Thread Thread
 
codevault profile image
Sergiu Mureşan

I remember you're a fan of C. Do you have any source code I can look at? I had lots of problems with having too many functions that didn't really make sense outside the context they were used.

Thread Thread
 
lobsterpants66 profile image
Chris Shepherd

I'm surprised you see too many functions as a problem. I would think that points to a structural problem in your project organisation.

I rarely put more than 5 lines in a function and one liners are quite common.

Thread Thread
 
codevault profile image
Sergiu Mureşan

That might be true.

Although breaking everything in even more functions does not help much. It just introduces even more confusion. Small comments are so much better even if they might get outdated at some point.

Are you the only person working on your projects or do you work on a team?

Thread Thread
 
lobsterpants66 profile image
Chris Shepherd

Oh it helps a lot. For example I can get all staff in one line of code.
I could just put it in my code with a comment.

Or I could put it as a function in a class that handles everything to do with staff.

Later on, I needed to handle errors, so it gets a try catch block around it, plus I add caching at the staff level. All is easy because I chose to separate it out earlier.

Why do you think
//Gets all staff

Is easier to understand than
GetAllStaff()

?

I have worked in teams and on my own and after twenty years of doing this I find it a much easier way to work.

Thread Thread
 
codevault profile image
Sergiu Mureşan

Sorry for the confusion, I meant explicitly in my project in C.

Thanks for the response!

I do agree that creating functions instead of commenting out a block is better but, creating functions from code blocks that are already readable enough, albeit large but specific enough that they are never gonna be reused is what I think hurts a project. Just this specific case.

From some really good code you extract a function with a lot of parameters that is never going to be reused again will hurt maintainability.

Thread Thread
 
lobsterpants66 profile image
Chris Shepherd

I guess language makes a lot of difference.
Personally I would never create a function with more than two or three parameters, instead I would bundle them into a class.

This can seen like a lot of work but modern Ides can make it easy to do and it usually helps with understanding your problem domain better.

Thread Thread
 
tux0r profile image
tux0r

There is no difference in the language IMO (except Assembler and COBOL)... :-)