Hamed F
Hamed F

Reputation: 41

Which one is better ? (Best practice) Create New class or Add extension methods in C#?

I want to know which one is better in programming

for Example I want to have Rijndael & TripleDES Encryptions in my project

I have 2 ways :

1 . Create an encryption class and have 4 methods in this

class Encryption

2 . Create 4 Extension Methods for String class

Encryption is only an example not my problem I want to know When use a new class When use an extension method for same purpose ?

Which one is better in OOP ? (or even both), Why ?

Upvotes: 1

Views: 208

Answers (2)

Dude Pascalou
Dude Pascalou

Reputation: 3179

TLDR:

In OOP, a class is better than an extension method.

The first reason is that a class and its methods are natively "Object Oriented" (OO). You can use inheritance, polymorphism and other OO stuff like that.

An extension method is a static method. A static method is not OO because you cannot use any OO stuff. And it is thread unsafe (many threads could access the same method and return different results, or worse, cause a deadlock).

Moreover, a extension method does not take precedence over instance method. For example, you cannot write a ToString extension method for string type. Well, you can, but it would never be called :

public static string ToString(this string input)
{
    return input + " whatever you want to do...";
}

Upvotes: 1

Thomas
Thomas

Reputation: 2984

To answer your question it is mostly a matter of taste for the specific programmer.

BUT

If you think that also other programmers need to use the program think about it how easy and self explaining things are to them.

If we take your example there as base. If you add an encrypt/decrypt to string does that look natural? Normally I wouldn't expect the string class to have such a method. Thus no.

Would its own class look natural? In this case yes.

Thus to sum it up: Look at what looks natural. Natural is that all things that are thematically related (stronlgy related as encryption/decryption is only weakly related to text itself) are in a single class. And if these methods extend the functionality of that class while being thematically linked they are candidates for extension methods.

As example lets take int. If you have a addTogether method that has 3 values but is not stronger related to a specific workflow than it is to int then that could be a candidate for an extension class for int. Else it would be in a class named "Calculations" for example and there as a normal method.

Upvotes: 1

Related Questions