There is an implementation class - Class P, which has around 10 concrete methods in it. My interest lies with one of the methods of this class.
Problem is my class is not encouraged to directly call Class P method. Also for my class to access Class P method i will need to add a condition in the desired Class P method. My question is which is more subtle-
inherit Class P into a new impl class and use this (given the no of methods in this class P i am not sure if this is right, as i will have overhead of unwanted extra methods).
or adjust my operation in the Class P method by adding few lines in Class P method.
If you need the method to be modified then it's not strictly reusable as is. Inheriting a class would provide the method as is, then you'd need to override it with a new version anyway. If you need to add code to execute before or after you could call the super but you could do the same thing by instantiating class P and calling it's method.
In addition inheriting for this purpose may make your intentions unclear as the next time someone or you looks at the code they'll ask, "why is class b a class p?".
Instead of achieving reusability through inheritance in this case, try componetizing the parts of the original method that wouldn't change and use those components in both classes.
Related
I work with a codebase where there are many classes with thousands of lines of code. I've noticed inconsistencies in style concerning prepending class names when using their methods and I'm trying to figure out the previous developer's reasoning. If we
import GeneralCode
in Class A, is it bad practice to write
GeneralCode.DoSomething()
in Class A since we already imported it (instead of simply using DoSomething())? I would think so, but I suppose it's also nice to know which methods come from which classes at a glance, since Class A imports many classes and uses methods from several of them.
EDIT: This is for VB.NET, not Java (sorry for the wrong tag, rough morning). I am new to VB.NET but GeneralCode and DoSomething() are not declared as static, neither is the import in Class A.
Might be something to do with VB.NET, but DoSomething() can indeed be used with or without prepending GeneralCode.
A method need to be prefixed with
The class name if it's a static method.
The name of the instance when it's not a static method.
Unless you are calling a method from your own class.
I have an interface: Show, and i have the implementation class calls ShowImpl, and also i have a implementation class calls ManageShowImpl. I have completed all the methods inside ManageShowImpl. Now i am doing Junit testing. The method i defined in the ManageShowImpl, for example: addShows(Show... shows), now i want to assign values to the show array: Show[], but in the interface: Show, i don't have setter method(which is not supposed inside interface), can some expert tell me how can i add the value to Show[].
If I understood correctly your issue, I think you can simply set values in your constructor:
public class ShowImpl implements Show{
private Show[] shows;
public ShowImpl(Show... shows){
this.shows = shows;
}
#Override
public void someInterfaceMethod(){
// ...
}
}
(I am not a junit expert, or even a beginner, but maybe I can inspire a few to answer. I have done a fair amount of testing.)
Given a class with a constructor, you can always create an instance, fill it with whatever data you want, and test it any way you want. Interfaces are a lot more limited. Testing aside, this is a very good thing. It limits the damage someone can do if they get hold of an interface implementation; it safely encapulates the data. But you cannot test an interface in isolation. You need to create an instance of an implementing class first. At that point you should fill in your array. Then pass it to a test method as an interface instance to test the interface.
That is, when child.update() is called, should the instance of a derived class implicity call all his superclasses's update() on itself before?
There's no good answer (in the languages I know). Sometimes you want to replace the super method. Sometimes you want to slip something in before it executes, and sometimes after. It does seem the extending class needs to know more about the details of the class it's overriding than it should have to. (This gets awkward with closed-source systems.) Also, the base class really wants to control the behaviour of the calling class sometimes, to force the super method to be called, which isn't right either. I think the best thing is for the super class to document its overridable methods as best it can so the overriding programmer can guess what to do.
The closest I've come to handing this properly and rightly is to make the target method so it cannot be overridden, then have it call a method or methods that do nothing but that can be overridden. Then the overriding class can override whichever methods interest it without being able to undermine the superclass.
The ultimate programming language will have a fool-proof solution to this problem.
No. Someone might need to override update() and wants to prevent exactly any call from a parent. In that case in implicit call would not only hurt performance it also might do things you don't want to.
It really depends on what the superclass / base-class function does. Sometimes I call it first, sometimes I call it last. Sometimes I call it conditionally, and once in a while, I don't call it at all.
Many times (this is coming from a C# background), the base class function just raises an event, and the child class overrides that method to get the event-like functionality. There are cases where the child doesn't want that event to be raised:
class Base {
public event EventHandler UnhandledError;
protected virtual void OnUnhandledError(Error error) {
if (UnhandledError != null)
UnhandledError(this, EventArgs.Empty);
}
}
class Derived : Base {
protected override void OnUnhandledError(Error error) {
if (HandleError(error))
return; // We took care of it. Don't raise the event.
// We couldn't handle it. Let the base class raise the event.
base.OnUnhandledError(error);
}
}
You are not wrapping a class into another, you are inheriting from a super-class.
Overriding super-class methods you should call super.method() only when you need to extend behavior of parent method().
I was reading about private constructor and found a few points that I couldn't understand. It said, if you declare a constructor as private:
That class cannot be explicitly instantiated from another class
That class cannot be inherited
Should be used in classes containing only static utility methods
My first question: Point 2 says the class cannot be inherited. Well, if you declare a class private then it would still satisfy this property. Is it because, if a class is private, it can still be explicitly instantiated from outside by another class?
My second question: I don't understand point 3. If I have a helper class which is full of static methods, I would never have to instantiate that class to use the methods. So, what is the purpose of a constructor in that class which you are never going to instantiate?
Answer for Java
Question 1 You're confusing a private class, with a class that has a private constructor. Private constructors are used mainly for static classes that are not meant to be instatiated (i.e. they just have a bunch of static methods on them).
Question 2 Exactly there is no need for a constructor so you have to explicitly create a private constructor so that it does not get a default constructer that the JVM will provide if none is defined
An empty class with no methods defined will always be given a no argument constructor by the JVM by default
I take java and c++ as an examples (not the best OO languages known, but very popular) - since you are not defining which languge do you mean.
Ad.2. In these languages you must either call superclass constructor explicitly or it is implicitly called for you. From a subclass you cannot call private methods (only public and protected) - this rule applies to constructors as well. This means if the class has only private constructors, there is no way to call one in subclass constructor. So you cannot subclass such class.
Ad. 3. It is just to avoid confusion - since this class is only a container for utility methods, there is no point in instantiating it. This way you can enforce this rule at compile time.
Let's say I have a Swing GUI that has to display a certain type of information in two different ways. From a design patterns perspective one would probably use the Strategy pattern here: create an interface that defines how the communication between the display component and the client works like this:
public interface Foo {
void showData(Data bar)
}
The real action is then done by different components that implement Foo and can be created and plugged in for doing the real work.
Now, what happens, if the real components are java.awt.Components? As I see it, it results in a mess of type casts because Component is a class. Let's assume an implementation like this one:
public class Baz extends Component implements Foo {
...
}
If I want to pass objects of class Baz around, the methods can either use "Component" as the parameter type or "Foo". The problem is that some methods need objects that are both Component and Foo (e.g. because they add the object to a JPanel and then supply the data calling the interface method showData()).
As I see it I have some choices to make this happen:
I can pass the reference as Component and cast to Foo. Before, I have to check that the reference is an instance of Foo and I have to handle situations where this requirement is not met. Another problem is that I have to communicate to clients of the method that the Component passed also has to implement Foo, which is awkward and error-prone.
I can do the same thing with Foo
I can add a method "Component getComponent()" to the Foo interface and the implementation would always return "this". This boilerplate method could be put into an abstract sub-class of Component. This solution means an interface method I don't want and an additional sub-class I don't need.
I can pass two references, one Component and one Foo reference to the same object. Internally, I'd have to make sure, though, that both references belong to the same object. And I have to deal with situations in which this requirement is not met.
I can use an abstract sub-class of Component and define the interface using abstract methods. This would allow me to pass references in a type-safe manner, but break with good OOP practices: keeping interfaces and implementations separate and also the interface segregation principle.
So, all of these solutions are merely workarounds. Is there any solution I'm missing? What should I do?
I would use the Strategy design pattern as you mentioned, but perhaps in a different context. The problem with trying to "shoe-horn" both Foo and Component into one class is that you could have combinations of implementations that would require duplicating code.
For example, imagine you have the following implementations of Component:
(Its been too long since Ive used Swing, these classes may not exist)
JPanel
JButton
JMenu
And you also had the following implementations of Foo
MyFoo
HisFoo
OurFoo
WhatTheFoo
And Imagine all the combinations of those: that's whats called a class explosion. This is the classic justification for the Strategy pattern.
I would create a sort of container class that uses a HAS-A relationship for each of the needed classes instead of using the IS-A relationship as follows:
(Im a c++ programmer, so you'll have to excuse the hybrid code :)
class ComponentFooHandler {
Component component_;
Foo fooImpl_;
inline Foo getFoo() {return fooImpl_;}
void setFoo(Foo f) {fooImpl_ = f;}
Component getComponent() {return component_;}
void setComponent(Component c) {component_ = c;}
void doAction() {
component_.someAction();
fooImpl_.anotherAction();
}
}
You would then have to create different implementations of Foo seperately. Then the Component and Foo implementations can be combined as needed with out having to duplicate Foo impl code. Notice also that you can call methods that like doAction() that can operate on both Foo and Component without knowing their details, similar to a Template Pattern.
To solve the issues with your original question:
When a Component is needed, call getComponent() on a handler instance
When a Foo is needed, call getFoo() on a handler instance
I would avoid creating methods that need both in one and split the method args into 2
Or just consider passing around a ComponentFooHandler