help with interfaces and abstract classes - oop

I'm recently getting a bit confused with interfaces and abstract classes and I feel I dont fully grasp it like I thought I did. I think I'm using them incorrectly. I'll describe what I'm doing at the moment, the problem I have faced, and then hopefully it be clear what I'm doing wrong if anything.
I wanted to write some classes that do some parsing of xml. I have different user types that have different parsing requirements.
My logic went as follows.
All parsers share a "parse" function in common and must have at least this function so I made an Interface with this function defined named IParse;
I start out with 2 user types, user type A and user type B. User type A & B share some basic functions but user type B has slightly more functions than A so I put the functions to parse what they share in an abstract class that both will extend called "ParseBase".
So now I have
// Interface
public interface IParser
{
function parse(xml:XML):void;
}
// Base Class
public class ParseBase()
{
public function getbasicdata():void{}
public function getmorebasicdata():void{}
}
//User type A
public class userTypeA extends ParseBase implement IParse
{
public function parse(xml:XML):void
{
getbasicdata()
getmorebasicdata()
}
}
//user type B
public class userTypeB extends ParseBase implement IParse
{
public function parse(xml:XML):void
{
getbasicdata()
getmorebasicdata()
}
public function extraFunctionForB():void
{
}
public function anotherExtraFunctionForB():void
{
}
}
The problem I have come up against now which leads me believe that I'm doing something wrong is as follows.
Lets say I want to add another function UserTypeB. I go and write a new public function in that class. Then In my implementation I use a switch to check what Usertype to create.
Var userParser:IParser
if(a)
{
userParser= new userTypeA();
}else if(b)
{
userParser= new userTypeB();
}
If i then try to access that new function I can't see it in my code hinting. The only function names I see are the functions defined in the interface.
What am I doing wrong?

You declare the new function only in userTypeB, not in IParser. Thus it is not visible via IParser's interface. Since userParser is declared as an IParser, you can't directly access userTypeB's functions via it - you need to either downcast it to userTypeB, or add the new function to IParser to achieve that.
Of course, adding a function to IParser only makes sense if that function is meaningful for all parsers, not only for userTypeB. This is a design question, which IMO can't be reasonably answered without knowing a lot more about your app. One thing you can do though, is to unite IParser and BaseParser - IMO you don't need both. You can simply define the public interface and some default implementation in a single abstract class.
Oher than that, this has nothing to do with abstract classes - consider rephrasing the title. Btw in the code you show, ParseBase does not seem to be abstract.

In order to access functions for a specific sub-type (UserTypeB, for example) you need the variable to be of that type (requires explicit casting).
The use of interfaces and abstract classes is useful when you only require the methods defined in the interface. If you build the interface correctly, this should be most of the time.

As Peter Torok says (+1), the IParser declares just one function parse(xml). When you create a variable userParser of type IParser, you will be allowed to call ony the parse() method. In order to call a function defined in the subtype, you will have to explicitly cast it into that subtype.
In that case IMO your should rethink the way you have designed your parsers, an example would be to put a declaration in your IParser (Good if you make this abstract and have common base functionality in here) that allow subtypes (parsers) to do some customization before and after parsing.
You can also have a separate BaseParser abstract type that implemnts the IParser interface.

Related

Kotlin extension functions vs member functions?

I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).
However, is there any advantage, in terms of code readability/structure, by using extension functions:
class Foo { ... }
fun Foo.bar() {
// Some stuff
}
As opposed to member functions:
class Foo {
...
fun bar() {
// Some stuff
}
}
?
Is there a recommended practice?
When to use member functions
You should use member functions if all of the following apply:
The code is written originally in Kotlin
You can modify the code
The method makes sense to be able to use from any other code
When to use extension functions
You should use extension functions if any of the following apply:
The code was originally written in Java and you want to add methods written in Kotlin
You cannot change the original code
You want a special function that only makes sense for a particular part of the code
Why?
Generally, member functions are easier to find than extension functions, as they are guaranteed to be in the class they are a member of (or a super class/interface).
They also do not need to be imported into all of the code that uses them.
From my point of view, there are two compelling reasons to use extension functions:
To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).
To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.
It sounds like #1 isn't a concern in your case, so it's really more down to #2.
Extension functions are similar to those you create as a utility functions.
A basic example would be something like this:
// Strings.kt
fun String.isEmail() : Boolean {
// check for email pattern and return true/false
}
This code can be written as a utility function in Java like this:
class StringUtils {
public static boolean isEmail(String email) {
// check for email pattern and return true/false
}
}
So what it essentially does is, calling the same function with the object you call on will be passed as the first parameter to the argument. Like the same function I have given example of in Java.
If you want to call the extension function created in kotlin from java, you need to pass the caller as the first argument. Like,
StringsKt.isEmail("example#example.com")
As per the documentation,
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
They are simply static functions with the caller as the first argument and other parameters followed by it. It just extends the ability for us to write it that way.
When to create extension functions?
When you don't have access to that class. When that class belongs to some library you have not created.
For primitive types. Int, Float, String, etc.
The another reason for using extension function is, you don't have to extend that class in order to use the methods, as if they belong to that class (but not actually part of that class).
Hope it makes a bit clear for you..
As mentioned in other answers, extension functions are primarily used in code that you can't change - maybe you want to change complex expression around some library object into easier and more readable expression.
My take would be to use extension functions for data classes. My reasoning is purely philosophical, data classes should be used only as data carriers, they shouldn't carry state and by themselves shouldn't do anything. That's why I think you should use extension function in case you need to write a function around data class.

Why is overriding of static methods left out of most OOP languages?

It is certainly not for good OOP design - as the need for common behavior of all instances of a derived class is quite valid conceptually. Moreover, it would make for so much cleaner code if one could just say Data.parse(file), have the common parse() code in the base class and let overriding do its magic than having to implement mostly similar code in all data subtypes and be careful to call DataSybtype.parse(file) - ugly ugly ugly
So there must be a reason - like Performance ?
As a bonus - are there OOP languages that do allow this ?
Java-specific arguments are welcome as that's what I am used to - but I believe the answer is language agnostic.
EDIT : one could ideally :
<T> void method(Iface<? extends T> ifaceImpl){
T.staticMeth(); // here the right override would be called
}
This will also fail due to erasure (in java at least) - if erasure is at work one needs (would need) to actually pass the class :
<T, K extends T> void method(Iface<K> ifaceImpl, Class<K> cls){
cls.staticMeth(); // compile error
}
Does it make sense ? Are there languages doing this already ? Is there a workaround apart from reflection ?
Speaking to C++
class Foo {
public:
static void staticFn(int i);
virtual void virtFn(int i);
};
The virtual function is a member function - that is, it is called with a this pointer from which to look up the vtable and find the correct function to call.
The static function, explicitly, does not operate on a member, so there is no this object from which to look up the vtable.
When you invoke a static member function as above, you are explicitly providing a fixed, static, function pointer.
foo->virtFn(1);
expands out to something vaguely like
foo->_vtable[0](foo, 1);
while
foo->staticFn(1);
expands to a simple function call
Foo##staticFn(1);
The whole point of "static" is that it is object-independent. Thus it would be impossible to virtualize.

Is there a common name for this code smell?

I refer to it as the "delivery boy". I've seen several variants of it but the issue is that a class has dependency for the sole purpose of passing it on to collaborators and never using the dependency itself.
(I'm using PHP because it's what I'm most familiar with but this is language agnostic)
class Dependency{}
class B {
public function setDependency(Dependency $dependency) {
//...
}
}
class A {
private $b;
private $dependency;
public function __construct(Dependency $dependency, B $b) {
$this->dependency = $dependency;
$this->b = $b;
}
public function foo() {
$this->b->setDependency($this->dependency);
}
}
Probably the most common variant I see in the wild is abusing inheritance for this purpose, having a property in the parent class which exists so that the child classes have access to the dependency even if the parent class never actually uses the dependency itself.
class Dependency{}
class A {
protected $dependency;
public function __construct(Dependency $dependency) {
$this->dependency = $dependency;
}
}
class B extends A {
public function foo() {
$this->dependency->bar();
}
}
I see this in code far more than I'd like and it doesn't make me very happy! I just wondered if there was a name for this so that I can link people to reading materials on why it's a bad idea. As it stands, I don't know what to search for!
I'm not aware of any name, but I kind of like Delivery boy... though I suppose some might consider the name borderline offensive.
Typically this problem is solved with either Dependency Injection or a Service Locator, although way too many people use Singleton for this (inappropriately).
I'm not familiar enough with PHP to know if PHP offers a real DI solution (as opposed to poor man's DI), but I think a service locator would be acceptable if there isn't (even though service locator is often a code smell in itself).
The problem related to inheritance in the second snippet looks like to me "Broken Hierarchy". This smell occurs when the base class and its derived class do not share an IS-A relationship. It is very common to find code that uses inheritance just for convenience (for reuse) and not because it makes sense to have a hierarchy where the participating classes are are related (by IS-A relationship).
(I borrowed the smell terminology (i.e. Broken Hierarchy) from the book "Refactoring for software design smells")

Injection of class with multiple constructors

Resolving a class that has multiple constructors with NInject doesn't seem to work.
public class Class1 : IClass
{
public Class1(int param) {...}
public Class1(int param2, string param3) { .. }
}
the following doesn’t seem to work:
IClass1 instance =
IocContainer.Get<IClass>(With.Parameters.ConstructorArgument(“param”, 1));
The hook in the module is simple, and worked before I added the extra constructor:
Bind().To();
The reason that it doesn't work is that manually supplied .ctor arguments are not considered in the .ctor selection process. The .ctors are scored according to how many parameters they have of which there is a binding on the parameter type. During activation, the manually supplied .ctor arguments are applied. Since you don't have bindings on int or string, they are not scored. You can force a scoring by adding the [Inject] attribute to the .ctor you wish to use.
The problem you're having is that Ninject selects .ctors based on the number of bound parameters available to it. That means that Ninject fundamentally doesn't understand overloading.
You can work around this problem by using the .ToConstructor() function in your bindings and combining it with the .Named() function. That lets you create multiple bindings for the same class to different constructors with different names. It's a little kludgy, but it works.
I maintain my own software development blog so this ended up being a post on it. If you want some example code and a little more explanation you should check it out.
http://www.nephandus.com/2013/05/10/overloading-ninject/

Best practice: ordering of public/protected/private within the class definition?

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out within a class?
A : 1) public methods 2) private methods 3) public vars 4) private vars
B : 1) public vars 2) private vars 3) public methods 4) private methods
C : 1) public vars 2) public methods 3) private methods 4)private vars
I generally like to put public static vars at the top, but then would a public static method be listed ahead of your constructor, or should the constructor always be listed first? That sort of thing...
I know it's finnicky but I just wondered: what are best practices for this?
PS: no I don't use Cc#. I know. I'm a luddite.
In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much. This is a more sensible way to organize code rather than by access modifier.
The best practice is to be consistent.
Personally, I prefer putting public methods first, followed by protected methods, following by private methods. Member data should in general always be private or protected, unless you have a good reason for it not to be so.
My rationale for putting public methods at the top is that it defines the interface for your class, so anyone perusing your header file should be able to see this information immediately.
In general, private and protected members are less important to most people looking at the header file, unless they are considering modifying the internals of the class. Keeping them "out of the way" ensures this information is maintained only on a need to know basis, one of the more important aspects of encapsulation.
Personally I like to have public at top, protected and then private. The reason for this is that when somebody cracks open the header he/she sees what he/she can access first, then more details as he/she scrolls down.
One should not have to look at the implementation details of a class in order to use it, then the class design is not done well.
I think I have a different philosophy on this than most. I prefer to group related items together. I can't stand having to jump around to work with a class. The code should flow and using a rather artificial ordering based on accessibility (public, private, protected etc. ) or instance versus static or member versus property versus function doesn't help keep a nice flow. So if I nave a public method Method that is implemented by private helper methods HelperMethodA, HelperMethodB etc. then rather than have these method far apart from each other in the file, I will keep them close to each other. Similarly, if i have an instance method that is implemented by a static method, I will group these together too.
So my classes often look like this:
class MyClass {
public string Method(int a) {
return HelperMethodA(a) + HelperMethodB(this.SomeStringMember);
}
string HelperMethodA(int a) { // returns some string }
string HelperMethodB(string s) { // returns some string }
public bool Equals(MyClass other) { return MyClass.Equals(this, other); }
public static bool Equals(MyClass left, MyClass right) { // return some bool }
public double SomeCalculation(double x, double y) {
if(x < 0) throw new ArgumentOutOfRangeException("x");
return DoSomeCalculation(x, y);
}
const double aConstant;
const double anotherConstant;
double DoSomeCalculation(double x, double y) {
return Math.Pow(aConstant, x) * Math.Sin(y)
+ this.SomeDoubleMember * anotherConstant;
}
}
This would be my ordering
Static Variables
Static Methods
Public Variables
Protected Variables
Private Variables
Constructors
Public Methods
Protected Methods
Private Methods
I use the following rules:
static before anything
variables before constructors before methods (i consider
constructors to be in the category of
methods)
public before protected before private
The idea is that you define the object (the data), before the behaviours (methods). Statics need to be separated because they aren't really part of the object, nor it's behaviour.
I used to care a lot. Over the last several years using modern IDEs pretty much everything is only 1 or 2 keystrokes away, I've let my standards relax substantially. Now, I start with statics, member variables, then constructors after that I don't worry about it much.
In C# I do let Resharper organize things automatically.
I generally agree with the public, protected, private order as well as the static data, member data, member functions order.
Though I sometimes group like members (getters & setters) I generally prefer listing members within a group ALPHABETICALLY so that they can be located more easily.
I also like lining up the data/functions vertically. I tab/space over to the right enough so that all names are aligned in the same column.
To each his own, and as Elzo says, modern IDEs have made it easier to find members and their modifiers in an easy way with colored icons in drop-down menus and such.
My take is that it is more important for the programmer to know what the class was designed for, and how it can be expected to behave.
So, if it is a Singleton, I put the semantics (static getInstance() class) first.
If it is a concrete factory, I put the getNew() function and the register / initialize functions first.
... and so on. When I say first, I mean soon after the c'tors and d'tor - since they are the default way of instantiating any class.
The functions that follow are then in:
logical call-order (e.g. initialize(), preProcess(), process(), postProcess() ), or
related functions together (like accessors, utilities, manipulators etc),
depending on if the class was meant primarily to be a data-store with some functions, or function provider with a few data members.
Some editors, like Eclipse and its offspring, allow you to reorder in the outline view the the vars and the methods, alphabetically or as in page.
The sequence of public followed by protected and private is more readable to me, It's better to describe the class logic in comments at top of the header file simply and function call orders to understand what a class dose and algorithms used inside.
I am using Qt c++ for a while and see some new sort of keywords like signal and slot I prefer to keep ordering like above and share my idea with you here.
#ifndef TEMPLATE_H
#define TEMPLATE_H
class ClassName
{
Q_OBJECT
Q_PROPERTY(qreal startValue READ startValue WRITE setStartValue)
Q_ENUMS(MyEnum)
public:
enum MyEnum {
Hello = 0x0,
World = 0x1
};
// constructors
explicit ClassName(QObject *parent = Q_NULLPTR);
~ClassName();
// getter and setters of member variables
// public functions (normal & virtual) -> orderby logic
public slots:
signals:
protected:
// protected functions it's rule followed like public functions
private slots:
private:
// methods
// members
};
#endif // TEMPLATE_H