OO Design Issue related to subclassing - oop

I have a parent bean having one instance variable like below :
public Class ParentBean {
protected boolean show; // this variable will be used to show some UI component
public void action() {
// update show variable here
}
public boolean isShow() {
return show;
}
}
Is it a good design if I want to reuse the "show" variable in a child bean (to show other UI component specific to child bean ) as shown below :
public Class ChildBean extends ParentBean {
// override the action method from parent bean
public void action() {
// update show variable here
show = true /false;
}
}
In effect , show variable is being updated by "childBean" by overriding action() method.
Is this a good design practice ? Otherwise same thing has to be repeated in ChildBean to get this work done.

If you use the show variable for the same purpose in the subclass, as you seem to be doing in this example, then obviously you should reuse it, because otherwise you just end up writing the same code twice, which is contrary to the point of OOP.
In general, in OOP, it is common to override superclass methods in subclasses, as well as modifying superclass instance variables, as long as you know what the variable you are modifying is being used for (you don't want to be randomly changing instance variables in classes that you don't completely understand, or don't have access to the source of, because you don't want any unfortunate side effects), so when it's your own code, this is absolutely fine.
As a general guideline, if your options are either to copy and paste a massive hunk of code and use it unchanged, or subclass and use the superclass' instance variables or functions, it's better to subclass. Otherwise, you're missing out on the point of OOP.

Changing the value in subclass will not affect superclass variable
This is fine with respect to the design. When a subclass object is instantiated, it will have a different copy of variable. and If superclass object is instantiated it will have different copy.

It is. Having a protected variable means you are allowed to modify it into parent or children classes (remember every single instance of each class has its own property values). So, if you have some generic functionality which is valuable for all the children:
Parent class:
public void action(){
//update show variable here
show = true;
}
Appart from that, if you want to add some extra functionality in a specifical child:
Child class:
#Override
public void action(){
super.action();
//Extra functionality goes here
//You can also access parent's 'protected' fields
if (show){
System.out.println("Shown");
}
}
An example of the use:
Parent p = new Parent();
p.action();//Prints nothing
Child c = new Child();
p.action();//Prints 'shown'

Related

Execute a method when object is changed (OOP)

I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change.
I have two classes:
public class SomeClass {
private OtherClass object;
public OtherClass getObject() {
return this.object;
}
public void setObject(OtherClass object) {
objectChanged();
this.object = object;
}
private void objectChanged() {
System.out.println("Object has changed");
}
}
public class OtherClass {
private int value = 5;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
The variable objectChanged should be called every time when variable "object" is changed. My first naive idea was to put the method call inside of set function. But what if you change the object after you set it? Like this:
SomeClass someObject = new SomeClass();
OtherClass otherObject = new OtherClass();
someObject.setObject(otherObject); //"Object has changed"
otherObject.setValue(10); //nothing happens yet
I need someObject to realize that object stored inside of it changed its value to 10, but how do i do it? Is it even possible in OOP?
It looks to be reasonable, but one should consider many things. This is why there is no automatic way to do it in general. It is not part of the OOP paradigm as such. If this would be some automatic behavior, it would cause huge overhead as it is not often needed to observe changes this way. But you can, of course, implement your way depending on your concrete requirements.
There are at least two approaches.
In MVVM (like WPF) there is an INotifyPropertyChanged interface (let's call it a pattern) you can use to trigger a notification yourself, mutch like you did with SomeClass. However when you are nesting objects, you need to wire up that mechanism.to cascade: you should do the same with OtherClass and also connect the actual instances to bubble up changes.
See: https://rehansaeed.com/tag/design-patterns/
An other option is the Observable pattern. Each time the object changes state, you emit an instance - the current instance. However, you should care to emit unmutable objects. At least by using an interface that makes it read-only. But you still need to wire up the object tree to react to the changes of nested objects.
If your platform supports reflection, and you create a proper toolset, you could make this wiring up quite simple. But again: this is not strictly related to the paradigm.

Extending vs Re-instantiating

I'm wondering which of the following two methods would be more efficient, or if it doesn't actually matter which route you take as the overhead is minuscule.
Essentially, is it better to instantiate a class (for example, 'Db') that you know is going to be used often in a parent class and simply extend the parent class whenever you want to use 'Db', or is it better to instantiate 'Db' separately in the constructor of the classes you want to use it.
Obviously the best route to take in terms of avoiding duplicate code would be to instantiate it in a parent class but just out of curiosity I was wondering if anyone has any insight into how significant/insignificant the effect on the server is for these two routes.
Route 1:
// Parent
class template {
public function __construct() {
$this->db = new Db();
}
}
// Child
class login extends template {
public function __construct() {
// Has access to $this->db
}
}
Route 2:
class login {
public function __construct() {
$this->db = new Db();
}
}
Thanks in advance.
It shouldn't matter performance wise.
If you extend the template class, you still have to instantiate the child class, which in turn will call the constructor of the parent implicitly. This means that in both cases, the DB class will be instantiated. Even worse, the extended class will probably be a little bit slower because it has the added overhead of an extra function call (that of the parent construct method).
That being said I strongly recommend to read up on composition over inheritance. Parent child relations are there to enforce an "is a" relationship. If you start extending the same class simply for performance reasons, chances are you are going to shoot yourself in the foot later on. It is simply unexpected behavior for most programmers to have unrelated classes extend from the same parent.

Where should I place variables or methods needed by several (but not all) child classes?

From the perspective of object-oriented best practices, where should I place a variable or method needed in some children of a parent class, but not others?
Ex.
Classes Button, Knob, Lever, and Switch inherit from parent class Device.
Button, Lever, and Switch need a boolean isOn, but Knob does not. Where would you define isOn?
Lever and Switch need a method Throw() that toggles isOn; Button uses isOn but does not use Throw() to handle it. Does this affect your placement of isOn, and where would you define the Throw() method?
The above is purely an example; let's assume that there are distinct properties of each child class that distinguish it and that there are commonalities that make it reasonable to use the inheritence model discussed.
When only a sub-set of sub-classes share functionality, this can be expressed with an interface that contains the methods in question, which is only implemented by the sub-classes that need them.
public interface OnOffable {
boolean isOn();
void toggleOnOff();
void turnOn(boolean is_on);
void turnOn();
void turnOff();
}
class Switch extends Device implements OnOffable...
If one or more of the functions is moderately complicated, you can create a static utility function that helps prevent redundant code. In this example, however, the "complicated-ness" is the need to keep the on-off state.
In this situation, you can create an OnOffableComposer which (my preference) does not implement OnOffable.
And actually, since this particular interface can be completely implemented (meaning it needs no protected or abstract function), it can actually be a "simple" implementation of it:
public class SimpleOnOffable implements OnOffable {
private boolean isOn;
public class OnOffableComposer(boolean is_on) {
turnOn(is_on);
}
public boolean isOn() {
return isOn;
}
public void turnOn(boolean is_on) {
isOn = is_on;
}
public void toggleOnOff() {
turnOn(!isOn());
}
public void turnOn() {
turnOn(true);
}
public void turnOff() {
turnOn(false);
}
}
Here's how it's used:
public class Switch extends Device implements OnOffable {
private final SimpleOnOffable smplOnOff;
public Switch(boolean is_on) {
smplOnOff = new SimpleOnOffable(is_on);
}
public boolean isOn() {
return smplOnOff.isOn();
}
public void turnOn(boolean is_on) {
smplOnOff.turnOn(is_on);
}
public void toggleOnOff() {
smplOnOff.toggleOnOff();
}
public void turnOn() {
smplOnOff.turnOn();
}
public void turnOff() {
smplOnOff.turnOff();
}
}
Although the composer is "simple", this all demonstrates the concept of choosing composition over inheritance. It allows for much more complicated designs than single inheritance allows.
It sounds like the wrong abstraction all around. At the very least, Knob doesn't belong with the others. I might inject a class between Device and the three closely-related devices. Perhaps something like BinaryDevice:
abstract class Device {}
abstract class BinaryDevice : Device {
abstract void Activate();
abstract void Deactivate();
}
class Switch : BinaryDevice {
void Activate() { // activate the switch }
void Deactivate() { // deactivate the switch }
}
// same for Lever, which honestly is really just a Switch with a different styling and may not even need to be a separate object
class Button : BinaryDevice {
void Activate() { // activate the button, then immediately call Deactivate() }
void Deactivate() { // deactivate the button }
}
Knob can also inherit from Device, but at this point there is no common functionality for a Device so it's not clear why that universal common base class is even necessary. As further functionality is added to the various devices there may indeed be common functionality to push up to the base class. Indeed, there are well established refactoring patterns for dealing with generalization like this.
With the classes above, I imagine there would be error handling for trying to invoke an action in an incorrect state. For example, it's difficult to imagine a scenario where a Button would need anybody to call Deactivate() on it, since it de-activates itself. (Though just as a real-life button can become stuck, so too can this one if the action it invokes hangs for some reason.) But in any event even the Activate() and Deactivate() on the other objects would still need to check state. You can't activate a switch that's already active, for example.
The point is, the clarity of an object model starts to make itself more apparent when terminology and real-world modeling is more carefully considered. A lot of times developers try to shoehorn terminology into a handful of common terms in order to maximize their use of things like inheritance, and unfortunately this often results in the wrong abstraction and a confused domain model.
Build your objects as they naturally exist, then look for patterns which can be abstracted into common functionality. Don't try to define the common functionality first and then force objects to fit that mold.
In general, I would say that if an element of a parent class is needed in some but not all of the children then an intermediate parent should be introduced.
When defining an inheritance hierarchy, it's a logical assumption that the children of a parent should share all properties of that common ancestor. This is akin to the way a biological taxonomy would work, and it helps to keep the code clean.
So let's have a look at the objects in your system (we'll use the "is a" relationship to help us figure out the inheritance hierarchy):
Button, Knob, Lever, and Switch
Each of these might indeed be called "Devices", but when we say "devices" most people will probably think of digital devices like phones or tablets. A better word for describing these objects might be "controls" because these objects help you to control things.
Are all objects Controls? Indeed they are, so every object will have Control as a parent in its inheritance hierarchy.
Do we need to further classify? Well your requirements are to have an on/off status, but it does not make sense for every control to have on/off status, but only some of them. So let's further divide these into Control and ToggleControl.
Is every Control a ToggleControl? No, so these are separate classes of objects.
Is every ToggleControl a Control? Yes, so ToggleControl can inherit from Control.
Are all objects properly classified and are all parent attributes shared by all children? Yes, so we're done building our inheritance hierarchy.
Our inheritance hierarchy thus looks like this:
Control (Code shared by all controls)
/ \
/ \
Knob ToggleControl (Code shared by all controls that can also be toggled - Adds isOn)
\
\
Button, Lever, Switch
Now, to the other part of your question:
Lever and Switch need a method Throw() that toggles isOn; Button uses isOn but does not use Throw() to handle it. Does this affect your placement of isOn, and where would you define the Throw() method?
Firstly, "throw" is a reserved word (at least in Java), so using method names that are similar to reserved words might cause confusion. The method might be better named "toggle()".
Button should (in fact it must) use toggle() to toggle it's isOn since it is a togglable control.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.

Encapsulation within class definitions

For example, do you use accessors and mutators within your method definitions or just access the data directly? Sometimes, all the time or when in Rome?
Always try to use accessors, even inside the class. The only time you would want to access state directly and not through the public interface is if for some reason you needed to bypass the validation or other logic contained in the accessor method.
Now if you find yourself in the situation where you do need to bypass that logic you ought to step back and ask yourself whether or not this need betrays a flaw in your design.
Edit: Read Automatic vs Explicit Properties by Eric Lippert in which he delves into this very issue and explains things very clearly. It is about C# specifically but the OOP theory is universal and solid.
Here is an excerpt:
If the reason that motivated the
change from automatically implemented
property to explicitly implemented
property was to change the semantics
of the property then you should
evaluate whether the desired semantics
when accessing the property from
within the class are identical to or
different from the desired semantics
when accessing the property from
outside the class.
If the result of that investigation is
“from within the class, the desired
semantics of accessing this property
are different from the desired
semantics of accessing the property
from the outside”, then your edit has
introduced a bug. You should fix the
bug. If they are the same, then your
edit has not introduced a bug; keep
the implementation the same.
In general, I prefer accessors/mutators. That way, I can change the internal implementation of a class, while the class functions in the same way to an external user (or preexisting code that I dont want to break).
The accessors are designed so that you can add property specific logic. Such as
int Degrees
{
set
{
_degrees = value % 360;
}
}
So, you would always want to access that field through the getter and setter, and that way you can always be certain that the value will never get greater than 360.
If, as Andrew mentioned, you need to skip the validation, then it's quite possible that there is a flaw in the design of the function, or in the design of the validation.
Accessors and Mutators are designed to ensure consistency of your data, so even within your class you should always strive to make sure that there's no possible way of injecting unvalidated data into those fields.
EDIT
See this question as well:
OO Design: Do you use public properties or private fields internally?
I don't tend to share with the outside world the 'innards' of my classes and so my internal needs for data (the private method stuff) tends to not do the same sort of stuff that my public interface does, typically.
It is pretty uncommon that I'll write an accessor/mutator that a private method will call, but I suspect I'm in the minority here. Maybe I should do more of this, but I don't tend to.
Anyway, that's my [patina covered] two cents.
I will often start with private auto properties, then refactor if necessary. I'll refactor to a property with a backing field, then replace the backing field with the "real" store, for instance Session or ViewState for an ASP.NET application.
From:
private int[] Property { get; set; }
to
private int[] _property;
private int[] Property
{
get { return _property; }
set { _property = value; }
}
to
private int[] _property;
private int[] Property
{
get
{
if (_property == null)
{
_property = new int[8];
}
return _property;
}
set { _property = value; }
}
to
private int[] Property
{
get
{
if (ViewState["PropertyKey"] == null)
{
ViewState["PropertyKey"] = new int[8];
}
return (int[]) ViewState["PropertyKey"];
}
set { ViewState["PropertyKey"] = value; }
}
Of course, I use ReSharper, so this takes less time to do than to post about.