Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to extend a class functionality in java?

for short, this could be paraphrased like "inheritance versus function library"

for example, I'd like to add a method to the javax.servlet.http.HttpServletRequest that gives me the whole body, a getBody() method that would read the body thru the getReader method, just to put an example.

In other languages, like ruby or javascript, you could add a method to the base class, or even to a specific instance, but in java I see this two choices...

  1. extend HttpServletRequest ( something like MyHttpServletRequest) and add the method

  2. or create an HttpServeletHelper static class, with static methods, with the following method

public static String HttpServeletHelper.getBody( HttpServletRequest request )

the first approach is more object oriented, and elegant, but forces you to cast your object every time you need it, and somehow you have to tell jsp to use your class...

the second approach is just a good old function library... which might be a good or bad thing depending on how you look at it...

what pros / cons do you see in each approach, and which one is the more recommended for this kind of situations?

like image 968
opensas Avatar asked Jul 05 '26 04:07

opensas


1 Answers

I would choose #2. HttpServletRequest is part of a framework, so Tomcat (or whatever) is going to instantiate it and hand it to your code. You won't get to choose whether to use your subclass. (Actually, with the rise of frameworks like Servlets, EJBs, etc, I find this problem to be rather common.)

Also, a lot has been written recently about over-reliance on inheritance as an anti-pattern. In Java, inheritance is a "scarce resource": for each class, you only get to do it once. You should reserve inheritance for things that are genuinely "sub-classes," not just to add some functionality here and there.

like image 193
Paul A Jungwirth Avatar answered Jul 07 '26 17:07

Paul A Jungwirth