Is a Class special when it has no members? - language-agnostic

I just realize some of my classes have no members. It has several public functions and maybe private functions and everything is passes through params. I realize functional programmers do this all the time but is this class considered special if it access nothing outside of the class and only uses its params for reading (except for out params and return values)?
I know this class can be static but static classes can modify outside variables. I want to know if this is a technique or maybe if a language may give additional benefits for writing it this way and etc.
-edit- This is looking like a wiki so lets make it one.

It is just called "stateless". Nothing really special about it.

There is nothing wrong with a class that has no members; controllers do this very frequently.
Yes, you could go static, but by not being static you allow for inheritance from your memberless class, which could add members along the way, if you so desired.

If there are no members, then there is no need for a class other than having a namespace. If you were programming in Python, then you would just put those methods into a module and don't bother with a class. If you are working in Java, then a a class is a must. If you are working in C++, it's up to you - but maybe you should consider using just a namespace, instead of a class, to make it less confusing.

Yes, this makes the class completely thread safe and thus no locking is required. To me, that is a fantastic attribute.

Sane programming languages allow you to define functions outside of classes when the functions do not require any persistent data - if you can define it in an appropriate namespace, all the better. If your language does not allow that, at least define them in a static class so it's clear that no state is accessed or mutated. Overall, though, this reminds me of an excellent article on the illogical abuse of classes in the name of "pure OOP".

I'd make the class static. I don't see what advantage it would give to keep it non-static. But then again - I'm a .NET developer, not Java. The languages are close, but there are many subtle differences I'm not aware of.

Remember that all methods of your class (even stateless) have one special variable -- pointer/reference to object - this (self, whatever) for which they are applied to.
Thus it is perfect sense in such stateless class if its methods could be overridden: in this case you have to have class to provide dispatching by this.
(Of course it's just emulating of first-class functions, so if your language already has ones it's no sense in this technique.)
At the moment I can't imagine why would you need stateless class without any virtual method.
Unless you want to have nice auto-complete in your IDE by typing objectName and dot :)

its simple class there is no specialty in it.
But i dont understand what is the use of having public or private methods when there in no member in it. because member methods are those which acts on particular instance's state.
Yes you can have static methods in it.

Related

What is the difference between Inappropriate Intimacy and Feature Envy?

Both smells are described in Fowler's book "Refactoring".
I know the meanings of those smells are, briefly:
Feature Envy is that a method in one object invokes half-a-dozen getting methods on another object.
Inappropriate Intimacy is that two classes depend on each others' private parts too often.
It looks like both smells indicate that part of one object depends on the other object too much.
Could someone explain the main difference between these two smells?
You described it pretty well.
Inappropriate Intimacy means compromising the other class's encapsulation, such as by directly accessing instance variables that aren't meant to be directly accessed. Very bad. Fix the grabby class to only use public features of the compromised class and, if possible, change the compromised class so that other classes can't get at its private features.
Feature Envy is when a method uses more public features of another class than it does of its own. Not as bad, because (assuming the other class's public features are safe to use) it won't lead to bugs. But it does lead to design entangling between the two classes. Fix by adding higher-level (better abstracted) public features to the envied class, or moving methods from the envious class to the envied class, so that the envious class has less methods to call.

Naming of classes providing the complete implementation of an interface, but which are designed to be extended / used as mixins

If you write an interface with a lot of methods, say IPerson, and you expect a lot of different implementations of it, it is quite common practice to provide an abstract class AbstractPerson which implements the bulk of the functionality.
Normally AbstractPerson is abstract, since you usually leave some key functionality unimplemented. In this case the naming makes sense.
But what is a good naming convention in case you already implemented all of IPerson, but still expect subclasses? Perhaps PersonMixin, PersonHelper, GenericPerson or simply Person? I think Person is a bit vague, since it doesn't clearly show the intended usage.
Although this is from the Framework Design Guidelines (for .NET), I think it applies equally to any language. The reccomendation is:
Avoid naming bases class with the Base suffix if the class is intended to be used in public APIs. If the library exposes the base class as a return type or parameter type, it should not have the Base suffix.
In general, if the class is public (or even private, although there is less risk in that case) and you name it PersonBase there is an implication that it is a base class. If at some point in the future the class hierarchy is refactored and PersonBase is no longer the base class you would want to rename PersonBase to something else which would most likely result in a breaking change for any consumer code.
I would simply name the class Person and let any derived classes use more specific names. I think Person is very clear and indicative of it's use as a generic (non-specific) person.
I think Person is just fine. The whole point is that you might specialize it to specific types of people, but it's still a person.
If it can be used as-is, I'd stick with Person. If not, I'd make it abstract (even if it has no abstract members) and call it PersonBase.

Can I change class types in a setter with an object-oriented language?

Here is the problem statement: Calling a setter on the object should result in the object to change to an object of a different class, which language can support this?
Ex. I have a class called "Man" (Parent Class), and two children namely "Toddler" and "Old Man", they are its children because they override a behaviour in Man called as walk. ( i.e Toddler sometimes walks using both his hands and legs kneeled down and the Old man uses a stick to support himself).
The Man class has a attribute called age, I have a setter on Man, say setAge(int ageValue). I have 3 objects, 2 toddlers, 1 old-Man. (The system is up and running, I guess when we say objects it is obvious). I will make this call, toddler.setAge(80), I expect the toddler to change to an object of type Old Man. Is this possible? Please suggest.
Thanks,
This sounds to me like the model is wrong. What you have is a Person whose relative temporal grouping and some specific behavior changes with age.
Perhaps you need a method named getAgeGroup() which returns an appropriate Enum, depending on what the current age is. You also need an internal state object which encapsulates the state-specific behavior to which your Person delegates behavior which changes with age.
That said, changing the type of an instantiated object dynamically will likely only be doable only with dynamically typed languages; certainly it's not doable in Java, and probably not doable in C# and most other statically typed languages.
This is a common problem that you can solve using combination of OO modelling and design patterns.
You will model the class the way you have where Toddler and OldMan inherit from Man base class. You will need to introduce a Proxy (see GoF design pattern) class as your access to your Man class. Internally, proxy hold a man object/pointer/reference to either Toddler or OldMan. The proxy will expose all the interfaces that is exposed by Man class so that you can use it as it is and in your scenario, you will implement setAge similar to the pseudo code below:
public void setAge(int age)
{
if( age > TODDLER_MAX && myMan is Toddler)
myMan = new OldMan();
else
.....
myMan.setAge(age);
}
If your language does not support changing the classtype at runtime, take a look at the decorator and strategy patterns.
Objects in Python can change their class by setting the __class__ attribute. Otherwise, use the Strategy pattern.
I wonder if subclassing is really the best solution here. A property (enum, probably) that has different types of people as its possible values is one alternative. Or, for that matter, a derived property or method that tells you the type of person based on the age.
Javascript can do this. At any time you can take an existing object and add new methods to it, or change its existing methods. This can be done at the individual object level.
Douglas Crockford writes about this in Classical Inheritance in JavaScript:
Class Augmentation
JavaScript's dynamism allows us to add
or replace methods of an existing
class. We can call the method method
at any time, and all present and
future instances of the class will
have that method. We can literally
extend a class at any time.
Inheritance works retroactively. We
call this Class Augmentation to avoid
confusion with Java's extends, which
means something else.
Object Augmentation
In the static object-oriented
languages, if you want an object which
is slightly different than another
object, you need to define a new
class. In JavaScript, you can add
methods to individual objects without
the need for additional classes. This
has enormous power because you can
write far fewer classes and the
classes you do write can be much
simpler. Recall that JavaScript
objects are like hashtables. You
can add new values at any time. If the
value is a function, then it becomes a
method.
Common Lisp can: use the generic function CHANGE-CLASS.
I am surprised no one so far seemed to notice that this is the exact case for the State design pattern (although #Fadrian in fact described the core idea of the pattern quite precisely - without mentioning its name).
The state pattern is a behavioral software design pattern, also known as
the objects for states pattern. This pattern is used in computer
programming to represent the state of an object. This is a clean way for an
object to partially change its type at runtime.
The referenced page gives examples in Java and Python. Obviously it can be implemented in other strongly typed languages as well. (OTOH weakly typed languages have no need for State, as these support such behaviour out of the box.)

Subclasses causing unexpected behavior in superclasses — OO design question

Although I'm coding in ObjC, This question is intentionally language-agnostic - it should apply to most OO languages
Let's say I have an "Collection" class, and I want to create a "FilteredCollection" that inherits from "Collection". Filters will be set up at object-creation time, and from them on, the class will behave like a "Collection" with the filters applied to its contents.
I do things the obvious way and subclass Collection. I override all the accessors, and think I've done a pretty neat job - my FilteredCollection looks like it should behave just like a Collection, but with objects that are 'in' it that correspond to my filters being filtered out to users. I think I can happily create FilteredCollections and pass them around my program as Collections.
But I come to testing and - oh no - it's not working. Delving into the debugger, I find that it's because the Collection implementation of some methods is calling the overridden FilteredCollection methods (say, for example, there's a "count" method that Collection relies upon when iterating its objects, but now it's getting the filtered count, because I overrode the count method to give the correct external behaviour).
What's wrong here? Why does it feel like some important principles are being violated despite the fact that it also feels like OO 'should' work this way? What's a general solution to this issue? Is there one?
I know, by the way, that a good 'solution' to this problem in particular would be to filter the objects before I put them into the collection, and not have to change Collection at all, but I'm asking a more general question than that - this is just an example. The more general issue is methods in an opaque superclass that rely on the behaviour of other methods that could be changed by subclasses, and what to do in the case that you want to subclass an object to change behaviour like this.
The Collection that you inherit from has a certain contract. Users of the class (and that includes the class itself, because it can call its own methods) assume that subclasses obey the contract. If you're lucky, the contract is specified clearly and unambiguously in its documentation...
For example, the contract could say: "if I add an element x, then iterate over the collection, I should get x back". It seems that your FilteredCollection implementation breaks that contract.
There is another problem here: Collection should be an interface, not a concrete implementation. An implementation (e.g. TreeSet) should implement that interface, and of course also obey its contract.
In this case, I think the correct design would be not to inherit from Collection, but rather create FilteredCollection as a "wrapper" around it. Probably FilteredCollection should not implement the Collection interface, because it does not obey the usual contract for collections.
Rather than sublcassing Collection to implement FilteredCollection, try implementing FilteredCollection as a separate class that implements iCollection and delegates to an existing collection. This is similar to the Decorator pattern from the Gang of Four.
Partial example:
class FilteredCollection implements ICollection
{
private ICollection baseCollection;
public FilteredCollection(ICollection baseCollection)
{
this.baseCollection = baseCollection;
}
public GetItems()
{
return Filter(baseCollection.GetItems());
}
private Filter(...)
{
//do filter here
}
}
Implementing FilteredCollection as a decorator for ICollection has the added benefit that you can filter anything that implements ICollection, not just the one class you subclassed.
For added goodness, you can use the Command pattern to inject a specific implementation of Filter() into the FilteredCollection at runtime, eliminating the need to write a different FilteredCollection implementation for every filter you want to apply.
(Note whilst I'll use your example I'll try to concentrate on the concept rather then tell you what's wrong with your specific example).
Black Box Inheritance?
What you're crashing into is the myth of "Black box inheritance". Its often not actually possible to separate completely implementations that allow inheritance from implementations that use that inheritance. I know this flys in the face of how inheritance is often taught but there it is.
To take your example, its quite reasonable for you to want the consumers of the collection contract to see a Count which matches the number items they can get out of your collection. Its also quite reasonable for code in the inherited base class to access its Count property and get what it expects. Something has to give.
Who is Responsible?
Answer: The base class. To achieve both the goals above the base class needs to handle things differently. Why is this the reponsibility of the base class? Because it allows itself to be inherited from and allowed the member implementation to be overriden. Now it may be in some languages that facilitate an OO design that you aren't given a choice. However that just makes this problem harder to deal with but it still needs be dealt with.
In the example, the base collection class should have its own internal means of determining its actual count in the knowledge that a sub-class may override the existing implementation of Count. Its own implementation of the public and overridable Count property should not impact on the internal operation of the base class but just be a means to acheive the external contract it is implementing.
Of course this means the implementation of the base class isn't as crisp and clean as we would like. That's what I mean by the black box inheritance being a myth, there is some implementation cost just to allow inheritance.
The Bottom Line...
is an inheritable class needs to be coded defensively so that it doesn't rely on assumed operation of overridable members. OR it needs to be very clear in some form of documentation exactly what behaviour is expected from overriden implementations of members (this is common in classes that define abstract members).
Your FilteredCollection feels wrong. Usually, when you have a collection and you add a new element into it, you expect that it's count increases by one, and the new element is added to the container.
Your FilteredCollection does not work like this - if you add an item that is filtered, the count of the container might not change. I think this is where your design goes wrong.
If that behaviour is intended, then the contract for count makes it unsuitable for the purpose your member functions are trying to use it for.
I think that the real issue is a misunderstanding of how object-oriented languages are supposed to work. I'm guessing that you have code that looks something like this:
Collection myCollection = myFilteredCollection;
And expect to invoke the methods implemented by the Collection class. Correct?
In a C++ program, this might work, provided that the methods on Collection are not defined as virtual methods. However, this is an artifact of the design goals of C++.
In just about every other object-oriented language, all methods are dispatched dynamically: they use the type of the actual object, not the type of the variable.
If that's not what you're wondering, then read up on the Liskov Substitution Principle, and ask yourself whether you're breaking it. Lots of class hierarchies do.
What you described is a quirk of polymorphism. Since you can address an instance of a subclass as an instance of the parent class, you may not know what kind of implementation lies underneath the covers.
I think your solution is pretty simple:
You stated that you don't modify the collection, you only apply a filter to it when people fetch from it. Therefore you should not override the count method. All of those elements are in the collection therefore don't lie to the caller.
You want the base .count method to behave normally, but you still want the count so you should implement a getFilteredCount method which returns the amount of elements post filtering.
Subclassing is all about the 'Kind of' relationship. What you're doing is not out of the norm but not the most standard use case either. You're applying a filter to a collection, so you can claim that a 'FilteredCollection' is a 'kind of' collection, but in reality you're not actually modifying the collection; you're just wrapping it with a layer that simplifies filtering. In any case, this should work. The only downside is that you have to remember to call 'getFilteredCount' instead of .getCount
The example falls into "Doctor, it hurts when I do this" category. Yes, subclasses can break superclasses in various ways. No, there is no simple waterproof solution to prevent that.
You can seal your superclass (make everything final) if your language supports this but then you lose flexibility. This is the bad kind of defensive programming (the good relies on robust code, the bad relies on strong restrictions).
The best you can do is to act at human level - make sure that the human that writes the subclass understands the superclass. Tutoring/code review, good documentation, unit tests (in roughly this order of importance) can help achieve this. And of course it doesn't hurt to code the base class defensively.
You could argue that the superclass is not well-designed for subclassing, at least not in the way you want to. When the superclass calls "Count()" or "Next()" or whatever, it doesn't have to let that call be overridden. In c++, it can't be overridden unless it's declared "virtual", but that doesn't apply in all languages - for example, Obj-C is inherently virtual if I remember correctly.
It's even worse - this problem can happen to you even if you don't override methods in the superclass - see Subtyping vs Subclassing. See in particular the OOP problems reference in that article.
It behaves this way because this is how object-oriented programming is supposed to work!
The whole point of OOP is supposed to be that a sub-class can redefine some of its superclasses methods, and then operations done at the superclass level will get the subclass implementation.
Let's make your example a little more concrete. We create a "Collection animal" that contains dog, cat, lion, and basilisk. Then we create a FilteredCollection domesticAnimal that filters out the lion and basilisk. So now if we iterate over domesticAnimal we expect to see only dog and cat. If we ask for a count of the number of members, would we not expect the result to be "2"? It would surely be curious behavior if we asked the object how many members it had and it said "4", and then when we asked it to list them it only listed 2.
Making the overrides work at the superclass level is an important feature of OOP. It allows us to define a function that takes, in your example, a Collection object as a parameter and operates on it, without knowing or caring whether underneath it is really a "pure" Collection or a FilteredCollection. Everything should work either way. If it's a pure Collection it gets the pure Collection functions; if it's a FilteredCollection it gets the FilteredCollection functions.
If the count is also used internally for other purposes -- like deciding where new elements should go, so that you add what is really a fifth element and it mysteriously overwrites #3 -- then you have a problem in the design of the classes. OOP gives you great power over how classes operate, but with great power comes great responsibility. :-) If a function is used for two different purposes, and you override the implementation to satisfy your requirements for purpose #1, it's up to you to make sure that that doesn't break purpose #2.
My first reaction to your post was the mention of overriding "all the accessors." This is something I've seen a lot of: extending a base class then overriding most of the base class methods. This defeats the purpose of inheritance in my opinion. If you need to override most base class functions then it's time to reconsider why you're extending the class. As said before, an interface may be a better solution, since it loosely couples disparate objects. The sub-class should EXTEND the functionality of the base class, not completely rewrite it.
I couldn't help but wonder if you are overriding the base class members then it would seem quite logical that unexpected behavior would occur.
When I first grok'd how inheritance worked I used it a lot. I had these big trees with everything connected one way or another.
What a pain.
For what you want, you should be referencing your object, not extending it.
Also, I'd personally hide any trace of passing a collection from my public API (and, in general, my private API as well). Collections are impossible to make safe. Wrapping a collection (Come on, what's it used for??? You can guess just from the signature, right?) inside a WordCount class or a UsersWithAges class or a AnimalsAndFootCount class can make a lot more sense.
Also having methods like wordCount.getMostUsedWord(), usersWithAges.getUsersOverEighteen() and animalsAndFootCount.getBipeds() method moves repetitive utility functionality scattered throughout your code into your new-fangled business collection where it belongs.

When should a method be static?

In addition, are there any performance advantages to static methods over instance methods?
I came across the following recently: http://www.cafeaulait.org/course/week4/22.html :
When should a method be static?
Neither reads from nor writes to instance fields
Independent of the state of the object
Mathematical methods that accept arguments, apply an algorithm to those
arguments, and return a value
Factory methods that serve in lieu of constructors
I would be very interested in the feedback of the Stack Overflow community on this.
Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.
You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.
Whether or not a method is static is more of a design consideration than one of efficiency. A static method belongs to a class, where a non-static method belongs to an object. If you had a Math class, you might have a few static methods to deal with addition and subtraction because these are concepts associated with Math. However, if you had a Car class, you might have a few non-static methods to change gears and steer, because those are associated with a specific car, and not the concept of cars in general.
Another problem with static methods is that it is quite painful to write unit tests for them - in Java, at least. You cannot mock a static method in any way. There is a post on google testing blog about this issue.
My rule of thumb is to write static methods only when they have no external dependencies (like database access, read files, emails and so on) to keep them as simple as possible.
Just remember that whenever you are writing a static method, you are writing an inflexible method that cannot have it's behavior modified very easily.
You are writing procedural code, so if it makes sense to be procedural, then do it. If not, it should probably be an instance method.
This idea is taken from an article by Steve Yegge, which I think is an interesting and useful read.
#jagmal I think you've got some wires crossed somewhere - all the examples you list are clearly not static methods.
Static methods should deal entirely with abstract properties and concepts of a class - they should in no way relate to instance specific attributes (and most compilers will yell if they do).
For the car example, speed, kms driven are clearly attribute related. Gear shifting and speed calculation, when considered at the car level, are attribute dependent - but consider a carModel class that inherits from car: at this point theyy could become static methods, as the required attributes (such as wheel diameter) could be defined as constants at that level.
Performance-wise, a C++ static method can be slightly faster than a non-virtual instance method, as there's no need for a 'this' pointer to get passed to the method. In turn, both will be faster than virtual methods as there's no VMT lookup needed.
But, it's likely to be right down in the noise - particularly for languages which allow unnecessary parameter passing to be optimized out.
Here is a related discussion as to why String.Format is static that will highlight some reasons.
Another thing to consider when making methods static is that anyone able to see the class is able to call a static method. Whereas when the mehtod is an instance method, only those who have access to an instance are able to call that method.