Good or Bad OOP? [closed] - oop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Assume there is an abstract class with a constructor that calls a protected abstract method that is yet to be implemented by the child class. Is this a good or bad idea? Why?

This is a bad idea.
You're basically creating inversion of control within a constructor. The method in the base class that is being called gets called before the base class data is initialized (in most languages), which is dangerous, as well. It can easily lead to indeterminate behavior.
Remember, in most languages, when you construct a class, all of the base class construction runs first. So, if you have something like: MyClass() : MyBaseClass() {}, typically, MyBaseClass's constructor runs in its entirety, then MyClass's constructor executes. However, by using a virtual method in the base class, you're calling an instance method in MyClass before it's fully initialized - which could be very dangerous.

This is a bad idea, because in most OOP languages, the child is initialized after the parent is initialized. If the abstract function is implemented in the child, then it may operate on data in the child under the incorrect assumption that it has already been initialized, which is not the case in parent construction.
Example:
class Base {
public:
Base() { virtualInit(); }
virtual ~Base() {}
protected:
virtual void virtualInit() {}
};
class Derived : public Base {
public:
Derived() : ptr_(new SomeObject) {}
virtual ~Derived() {}
protected:
virtual void virtualInit() {
// dereference ptr_
}
private:
scoped_ptr<SomeObject> ptr_;
};
In the example above, Base::Base() gets executed before Derived::Derived(), which is responsible for initializing ptr_. Hence, when virtualInit() is called from Base::Base() it dereferences an uninitialized pointer, leading to all sorts of trouble. This is why ctors and dtors should call only non-virtual functions (in C++), final functions (in Java), or the language-specific equivalent.

I can't see the reasoning of why you would want to do this, let alone qualify it. Sounds like your trying to inject some functionality into the object. Why wouldn't you just overload the constructor or create a property that can be set so that you can inject the functionality through composition or even create the constructor with a parameter which is the IOC object.
As another has already posted, it does depend on the context in which your trying to solve a particular problem. The natural fit would be to adhere to an interface, develop an abstract class, and overload the constructor in each implementation. Without further information I can only comment on what has been posted in your question.
This design you have can not be regarded good or bad. Simply from the fact that it may be the only way you can achieve what your trying to do.

It is only then a GOOD idea, IFF you can manage it to not shoot in your own foot. But anyway, OOP is always prone to bad designs; so if your language allows other paradigms than OOP, to use OOP in this case is definitely a BAD choice.
At least in C++,
the child class defines in which sequence all the initialisations are made; that are the initialisations of all member-variables and the constructors of all parent classes. This has to be considered!
Alternatively, you could give the constructor (as parameter) a pointer to a specific function (I would prefer static functions), instead of calling an abstract member-function. This could be a far more elegant and sane solution; and this is the usual solution in (probably all) non-OOP languages. (in java: A pointer to one function or a list of functions is the design pattern of an interface and vice versa.)

Related

How do you avoid subclass call-backs when using Composition?

So I tend to favour composition over inheritance and I would like non-inheritance answers for this question.
There appears to be circumstances when using composition when there is some code in the superclass that requires a call to code in the subclass. This makes for unscaleable inheritance hierarchies which defeats the purpose of using composition in the first place. Here's a demonstration of the problem in C# (although this is a general oop question):
public interface IChemistry
{
void SeparateAtom(Atom atom);
void BreakBond(Bond bond);
}
public class BaseChemistry : IChemistry
{
public void SeparateAtom(Atom atom)
{
//possible extra logic here
for(int i=0;i < atom.BondCount;i++)
{
//maybe extra logic here etc.
BreakBond(atom.Bonds[i]);
}
}
public void BreakBond(Bond bond)
{
//do some bond breaking logic here
}
}
public class RealisticChemistry : IChemistry
{
private BaseChemistry base;
public RealisticChemistry(BaseChemistry base)
{
this.base = base;
}
public void SeparateAtom(Atom atom)
{
//subclass specific logic here perhaps
base.SeparateAtom(atom);
}
public void BreakBond(Bond bond)
{
//more subclass specific logic
base.BreakBond(bond);
}
}
As you can see with this design there is a glaring problem. When the subclass' SeparateAtom() method is called it executes some of it's own logic and then delegates the rest to the base class which will then call the BreakBond() method on the base class, not on the subclass.
There are various solutions I can think of for this and almost all of them have pretty substantial setbacks:
Copy and paste. The worst option in this case would be to simply copy the loop (and additional logic) within the base class' SeparateAtom() method, to the subclass' one. I don't feel that it is necessary to explain why copy and paste is not the best practice. Another option could be to package some of the extra logic around the loop into extra methods so that it's just the loop that is copied. But the calls to the additional methods are still copied, and breaking things up into multiple methods could break encapsulation. For example what if some of that logic is dependent on the specific context of SeparateAtom()and could lead to faulty data if called out-of-context by someone who does not know the code very well?
Listen to or observe bond breaking events in base class. This solution seems problematic to me because the way in which base class functionality should be extended becomes unclear. For example, without prior knowledge if one were to try to extend the class they might intuitively implement the design above and interpret the listener as optional, when it is in fact required if one wants to extend bond breaking behaviour.
Make the base class require a delegate. For example, the base class could require a reference to a IBondBreakDelegate which is called inside of BondBreak(). This has a similar problem to the listener approach in that the mixture of composition and other approaches makes the intended usage of the base class unclear. Also, even though now there is a delegate which is actually required, thus making the intended usage a little more clear, the base class can now no longer function on its own. Also if one needs to extend the hierarchy with an additional subclass (for example public class MoreRealistiChemistry etc.), how would one go about extending the delegated behaviour through composition?
Delegate everything instead of composition. I would prefer not to go down this route because when classes need extra functionality the amount of delegates needed increases (or the amount of methods in the delegates does). Also what if some of the delegated behaviour is optional? Then either there needs to be separate optional delegates for each behaviour that the subclass implements, or you end up with lots of empty method bodies in the subclass.
In general when I commit to a type of design, I would like to do so wholeheartedly. Of course in the real-world there are a ton of caveats. But I feel like this one must be so common that someone might know a good work-around. Any ideas?
(I cannot add a comment because of insufficient reputation, but I want to point out two things.)
First, your code does not compile because the classes do not implement IChemistry.
Second, 'favour composition over inheritance' is only a guideline and is not meant to be applied mindlessly. If the model that is under consideration for the solution requires either inheritance or composition, you should choose composition.
For this particular question, inheritance (or rather, specialisation) is the more sensible approach.

Call another class static method results in coupling

In OOP we don't want coupling of classes. If I want to use an instance of class b within class a I can use dependency injection.
However if I want to use static methods of class b within class a I dont see any option but to "require" or "import" class b in the class a class file. This ends up with coupling between the classes - going against OOP principles. But the alternative is to rewrite the static method of class b as a static method in class a - going against the DRY principle. What is the right way?
This question was flagged as a possible duplicate of How to use Dependency Injection with Static Methods? but I feel that my question is asking from a more generic perspective on using another class' static methods. The think the question and accepted answer in the possible duplicate is more specific to a use case, but would not apply for example to a mere utility static method in the external class. My question aims to seek answer from a general oop perspective.
There are a variety options here and the specific use case is important in deciding what you may want to do. So, the big three would be...
Migrate the static method off Class B and into a shared library class, which is purely a holder for static methods and is never instantiated (in Java you'd make the constructor private and the class final). Then both class A and class B can access the method without depending on each other and without violating the DRY principle and the dependency on the library class is no better nor worse than relying on a static method defined on the same class.
If you're talking about a static method which is really something that best lives on class B then you can hide that method call behind some kind of a provider instance which is dependency injected into class A, with the provider implementation simply calling the static method on B. If you wanted to be really evil then the provider could also be injected into instances of B, but that would probably be overkill.
The static method can be changed to be an instance method on a new class which is dependency injected into both A and B. Sometimes this has a side-benefit of allowing you to hide some state in the instance rather than having to pass parameters into an otherwise stateless method.
Note that static methods in general cause problems in OO terms so only really the third options is a 'clean' one that really decouples classes and properly allow for coding to interfaces.

Scala and encapsulation?

Since I started to study OOP encapsulation was always something that raised questions to me. Getters and setters in 99% of the cases seemed like a big lie: what does it matter to have setter if it changes the reference of the private field, and getter that returns reference to mutable object? Of course there are many things that make life easier with getters and setters pattern (like Hibernate that creates proxies on entities). In Scala there is some kind of solution: don't lie to yourself, if your field is val you have nothing to fear of and just make it public.
Still this doesn't solve the question of methods, should I ever declare a method private in Scala? Why would I declare a method private in Java? Mostly if it's a helper method and I don't want to pollute my class namespace, and if the method changes our internal state. The second issue doesn't apply (mostly & hopefully) to Scala, and the first one could be simply solved with appropriate traits. So when would I want to declare a method private in Scala? What is the convention for encapsulation in Scala? I would highly appreciate if you help me to order my thoughts on subject.
Getters and setters (or accessor/mutator methods) are used to encapsulate data, which is commonly considered one of the tenets of OOP.
They exist so that the underlying implementation of an object can change without compromising client code, as long as the interface contract remains unchanged.
This is a principle aiming to simplify maintenance and evolution of the codebase.
Even Scala has encapsulation, but it supports the Uniform Access Principle by avoiding explicit use of get/set (a JavaBean convention) by automatically creating accessor/mutator methods that mimics the attribute name (e.g. for a public val name attribute a corresponding def name public accessor is generated and for a var name you also have the def name_= mutator method).
For example if you define
class Encapsulation(hidden: Any, val readable: Any, var settable: Any)
the compiled .class is as follows
C:\devel\scala_code\stackoverflow>javap -cp . Encapsulation
Compiled from "encapsulation.scala"
public class Encapsulation {
public java.lang.Object readable();
public java.lang.Object settable();
public void settable_$eq(java.lang.Object);
public Encapsulation(java.lang.Object, java.lang.Object, java.lang.Object)
}
Scala is simply designed to avoid boilerplate by removing the necessity to define such methods.
Encapsulation (or information hiding) was not invented to support Hibernate or other frameworks. In fact in Hibernate you should be able to annotate the attribute field directly, all the while effectively breaking encapsulation.
As for the usefulness of private methods, it's once again a good design principle that leads to DRY code (if you have more than one method sharing a piece of logic), to better focusing the responsibility of each method, and to enable different composition of the same pieces.
This should be a general guideline for every method you define, and only a part of the encapsulated logic would come out at the public interface layer, leaving you with the rest being implemented as private (or even local) methods.
In scala (as in java) private constructors also allows you to restrict the way an object is instantiated through the use of factory methods.
Encapsulation is not only a matter of getter/setter methods or public/private accessor modifiers. That's a common misconception amongst Java developer who had to spend to much time with Hibernate (or similar JavaBean Specification based libraries).
In object-oriented programming, encapsulation not only refers to information hiding but it also refers to bundling both the data and the methods (operating on that data) together in the same object.
To achieve good encapsulation, there must a clear distinction between the those methods you wish to expose to the public (the so called public interface) and the internal state of an object which must comply with its data invariants.
In Scala the are many ways to achieve object-oriented encapulation. For example, one of my preferred is:
trait AnInterface {
def aMethod(): AType
}
object AnInterface {
def apply() = new AnHiddenImplementation()
private class AnHiddenImplementation {
var aVariable: AType = _
def aMethod(): AType = {
// operate on the internal aVariable
}
}
}
Firstly, define the trait (the public interface) so to make immediately clear what the clients will see. Then write its companion object to provide a factory method which instantiate a default concrete implementation. That implementation can be completely hidden from clients if defined private inside the companion object.
As you can see the Scala code is much more concise of any Java solution

OOP: What is the correct terminology for talking about methods and attributes? Both of classes, and their instances? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Say I have a class in a programming language:
class name {
variable_name = 1;
method_name(x) {
// return something
}
}
foo = new name();
print(foo.method_name(foo.variable_name));
How correct is the following? Can we make it more correct?
If I want to talk about a specific instance of a method (foo.method_name), would I say 'the method_name-method of the object foo'? Or something else? Or does talking about the instance of a variable of method make no sense?
If I want to talk about a general object of any name, and refer to its method_name-method or variable, what would I say? Would I say 'the method_name-method/variable_name-variable of the class name?' or something else?
Thank you for your time.
Kind regards,
Marius
Talking about a specific instance of a method doesn't really make any sense as you say. Usually we talk about instances of classes - objects - and their methods. Thus one would normally talk about something like "calling method_name on foo" or simply foo dot method_name.
That's a fine way of saying it. In my experience it doesn't really matter all that much in day to day communication as the method really does the same thing anyways, just with different values in it's scope. It's what it does that really matters (e.g. accelerate() or toString()). Perhaps the most important part when talking about methods, variables etc. is communicating clearly if they happen to be static - i.e. not belonging to any given instances. In day to day speak I wouldn't make any effort to differentiate very clearly between "then we can just call accelerate on our car instance" and "the car class has a method named accelerate" (it's given that this is a non-static method) - I might however specify that "our car class has a static method to help us calculate acceleration.
In a nutshell:
Classes: (which may be instantiated to objects)
can have -
(non-static / instance) members
- public
- methods
- properties
- private
- methods
- properties
(static / class) members
- public
- methods
- properties
- private
- methods
- properties
However, methods have/can also be called messages, selectors, or behaviours (depending on the language in question, and in particular contexts.) It's occasionally considered incorrect to call them functions, however no one in their right mind should take you to task over such things. (notably the appearance of the keyword function in ECMAScript shows its level of acceptability. As a rule of thumb, the language domain would always define correctness, otherwise generally the term is fine/understandable but can lead to ambiguity.) Similarly properties are variously called, fields, attributes or variables.
An alternative name for non-static methods or properties is to call them instance methods or properties. While static methods / properties may be referred to as class methods / properties. By the way, ommitting the non-static qualifier, is usual and implicit.
As a general guideline, refer to the language under use to determine the correct terms, as they are specific to the various language cultures.
The assumption in writing this, is that there's no need to outline the scope/access differences of these class members. If that's required, I'd be happy to add a note.

When is a class too big? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I tend to create very large classes that have 30-40 (or more) methods. How many methods are too many? Are there any "smells" or rules of thumb to use?
Step one is to adhere to the Single Responsibility Principle. If you can't say in one sentence what your class does, then it probably does too much.
Once you've narrowed that down, I don't know that the number of methods really matters as long as your methods don't do too much.
I'll bite. Without doing much more than wading into the very shallow edges of the deep waters of O-O design, I'll through a couple of my rules of thumb:
Static properties are highly questionable. Question yourself strongly about whether or not they are really needed.
Most properties/attributes of a class should be private (accessable only by the object instance) or protected, accessable only by an instance of the class or of a derived class (subclass).
If a property/attribute of a class is visible to the general public, it should most likely be read-only. For the most part, the state of an object instance should change only by its responding to a method asking it to do something useful (e.g., you request that a window move itself, rather than explicitly setting is origin on the coordinate plane).
Public Getter/Setter methods or properties are questionable as they primarily expose object state (which see item #2 above).
Public methods should primarily expose the logical operations (messages) to which an object instance responds. These operations should be atomic (e.g., for the object to be in a logically consistent internal state, it should not depend on an external actors sending it a particular sequence of messages). Object state should change are as result of responding to these messages and should be exposed as a side effect of the message (e.g., a window reporting its location as a side effect of asking it to move is acceptable).
The above should cut down the public interface to your objects considerably.
Finally, if your object has more than a few messages to which it responds, you likely have a candidate for refactoring: is it really one monolithic object, or is it an assembly of discrete objects? "More than a few", of course, is a highly subjective (and contextual) number -- I'll throw out 10-12 as a reasonable limit.
Hope this helps.
There are lots of books out there on O-O design, analysis and modelling.
As others have said, a class is too big when it is trying to do more than one thing and violates the Single Responsibility Principle.
An excellent book on this and other topics (and one I strongly recommend for any developer) is Clean Code by Bob Martin.
static classes such as Math are likely to have lots of methods. It would be confusing to split them.
A general guideline for design: if a reasonable person's first reaction to a <set of things> could plausibly be "That's too many <thing>s!", then it's too many <thing>s.
Number of methods by itself is not a reliable indicator. What if 20 of those are just property getters?
Try metrics that are more concrete, though this is always a judgment call. There is a list of 'code smells' here.
It's all relative but check out the single responsibility principle:
In object-oriented programming, the
single responsibility principle states
that every object should have a single
responsibility, and that
responsibility should be entirely
encapsulated by the class
A rule of thumb i've thought of for SRP: Count your usings/imports/includes. If your class has more than half a dozen there's a good chance that you're violating the SRP. But that's a relative idea as well. Certain patterns such as facades will violate this rule out of necessity. E.g. as in simplifying and hiding a complex subsytem.
A point about it is taken in the "Effective C++" 3rd edition:
"Prefer non-member, non-friend functions to member functions". What this means that you should keep your class reasonable small because big classes tend to be difficult to expand (the do not scale well)
You could also check you class for branches. If your class contains may "if's" or "switch'es" there is a high chance that your class responsibility has dissolved. If this is the case refactoring and cutting the responsibilities into smaller parts may lead to smaller classes.
Best Regards,
Marcin
It depends.
If you are in Java with get/set pairs for each field, I'm not surprised. But if each of those methods are 100+ line beasts, that would be a smell.
It depends on whether or not you can split the class in to subclasses.
Edit: What I mean is that you should ask yourself "does this method apply to this class or would it belong to a subclass?"
For example,
Class Animal
- dog_bark()dog_bark() could be moved to a class named Dog, and the method renamed to bark()
There is never a thing as too large of a class, when the PHP interpreter reads your code it compiles into one large executable black of code so splitting them up makes little difference on performance.
BUT:
When it comes down to programming you should never really need 40+ methods in one class, and should be split up into there entites.
Example
class HTTP
{
/*
* Base functions for HTTP Fetching / transferring / Sending
* so when it comes to single responsibility this would be the the fetch / set in HTTP
*/
}
then you would be more specific with your subclasses such as
class YoutubeUploader extends HTTP
{
/*
* This class is responsible for uploading to youtube only
*/
}
class YoutubeDownload extends HTTP
{
/*
* This class is responsible for downloading to youtube only
*/
}
class CronRunner extends HTTP
{
/*
* This class is responsible for Running your HTTP Cron Tasks
*/
}
no if you did not have that BASE HTTP Class you would have to define methods in all three sub classes to transfer data via the HTTP Protocol.
Splitting your classes up unto single responsibilities gives a more structured framework resulting in less code and more outcome.
Everyone ahs already mentioned the: Single Responsibility Principal but its something you should really understand.
There's also ways to reduce code in classes, take this example
class User
{
public function getUsername()
{
return $data['username'];
}
public function getPermissions()
{
return $data['permissions'];
}
public function getFirstname()
{
return $data['firstname'];
}
}
this are not really needed when you can do:
class User
{
public function __call($method,$params = array())
{
if(substr(0,3,$method) == "get")
{
$var_name = substr(3,strlen($method),$method);
return $data[$var_name];
}
}
}
This would take car of any method called that starts with 'get' and it takes the last portion of the string and searches the array.
In general a class should be designed to do one thing and to do it well. Now, with your example of the Math class, it can act as a facade to seperate implementations. Or it can be split up into hierarchy:
public abstract class Math
{
abstract Solve(IMathPayload);
abstract CanSolve(IMathPayload);
}
public class LinearMath : Math {}
public class DifferentialEquasionMath: Math {}
One strategy I like to follow is to create a 'Handle' class for each data model object. Because the handle is responsible for only modification of
that data object, it follows SRP. If I need to create classes outside of data object modification, at least I know most of the code already is SRP compliant.