Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class vs Utility class

Which of the two should be preferred?

There are some methods which are called by class A, B and C.

Should those methods be encapsulated in a class D (base of A, B and C) ?

OR

Should those methods be encapsulated in a class U and other classes creats it's object to use the methods as required.

On what basis decision should be taken?

Thanks.

like image 480
Azodious Avatar asked Mar 15 '11 13:03

Azodious


People also ask

What are utility classes?

Utilities are simple HTML classes typically scoped to a single CSS property, like border-style or background-color . Utilities can be used additively to style an object from scratch or to override a style defined in component CSS.

What is the base class for?

What Does Base Class Mean? A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).

When should I use util classes?

Whenever a common block of code needs to be used from multiple places, we can create utils class. Example: I want to verify whether a text is null or empty. This will be used in several places in my project.

What are utility classes in C#?

Utility Class (. NET Micro Framework) provides a collection of helper functions you can use to configure settings for security, collections, driver manipulation, time, and idle CPU usage.


2 Answers

You should make a static utility class.

Only use inheritance if it's actually meaningful—if A, B, and C actually are a D.

like image 186
SLaks Avatar answered Oct 25 '22 13:10

SLaks


I'd base the decision on what the methods are doing, if they're doing things specific to classes A, B and C then they should be in the base class. This helps keep code clean, by hiding class-related functionality away from the rest of the system. (of course, I'm assuming that A, B and C either already inherit from D, or are obviously related)

If they're doing things with other types, that aren't inherent in what A, B and C do, then in order to maximise opportunities for reuse they should be in a utility class.

If they're doing things with other types that are specific to that other type (e.g. pretty-printing a datetime) consider making them extension methods for that type.

like image 31
Massif Avatar answered Oct 25 '22 12:10

Massif