Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How/When to write reusable methods in OOP

Tags:

c#

oop

code-reuse

I often find myself in a situation where i am repeating two,three lines of code in a method multiple times and then think whether i should put that in a separate method to avoid code duplication. But then when i move those lines out of the method i find that the method just created is not reusable, was used only one time or requires an overload to be useful for another method.

My Question is what sort of patterns should we be looking for that indicate we should create a new method. I appreciate your response.

like image 680
Abdul Waheed Avatar asked Dec 23 '11 03:12

Abdul Waheed


2 Answers

Don't put too much functionality in one method/class. Try to follow the single responsibility principle. It'll take some time getting familiar with that approach. But once you reach that level, you'll notice that it's done all by itself. Before coding, try to ask yourself, what functional units your concept includes.

For example, you want to develop an application, that can index the content of pdf files. It's just fictional, but at first sight, I could identify at least three components:

  1. PdfParser - this provides you with the content of a pdf
  2. Indexer - gets input from parser and counts meaningful words
  3. Repository - it's for persistence; this could be made generic; so just say repository.Get<IndexData>(filename) or something

You should also try to code against interfaces. Especially when some kind of UI is involved. For example, you are developing a chat client with WinForms. If you follow the MVC/MVVM-pattern, you can easily (i.e., easier than coding against a Form object) use your original logic with a WPF version of the client.

like image 197
Matthias Avatar answered Oct 03 '22 08:10

Matthias


I would start by reading about the DRY principle (Don't Repeat Yourself) hopefully it will give you a good answer for your question, which is a question that all developers should be asking themselves by the way, great question!!

See Don't repeat yourself

I wanted to leave it at DRY because it is such a simple but powerful concept that will need some reading and a lot of practice to get good add. But let me try to answer directly to your question (IMHO),

If you can't give your method a name that reflects exactly what your method is doing, break it into pieces that have meaning.

You'll find yourself DRYing up your code with ease, reusable pieces will show up, and you probably will never find yourself repeating code.

I would do this even if it meant having methods with only couple of lines of code.

Following this practice will give meaning to your code, make it readable and predictable, and definitely more reusable

like image 33
Bassam Mehanni Avatar answered Oct 03 '22 06:10

Bassam Mehanni