Should a class name reflect the class itself or instances of the class? - naming-conventions

I have a class named 'Material'
The class itself represents an effect, but instances of that class represent a material.
Should I call the class 'Effect' or 'Material' ?

Apply the Single Responsibility Principle (SRP) and make two classes for two represented concerns.

What environment are you working in?
I'd keep both class and instances of classes representative of the material and employ a subclass for effect - particularly if the effect is coupled tightly with the material as is often the case. This will allow for better management as your effect arrays become more sophisticated.

Related

Object-Oriented Design - Specialization: Inheritance vs. Attributes

I usually come across some design problems in which I have the choice to either specialize a class by inheriting it by a sub class, or specialize the class by defining an attribute for it that classifies it. For example, for the collection of components of a car, we can either define classes (e.g. Wheel, Tire, Door ... etc), or we can define a single class "CarComponent" which have an attribute called "Type" that takes a value from an enumeration that list the different types of car components.
How can we compare those two approaches, and what design patterns would recommend each of them?
Thanks.
Inheritance is about changing behaviour. If you're not changing behaviour, you have no need for a subclass. Inheritance should never be about creating a class for each noun, no matter how nice it looks.
What behaviour does CarComponent have in the context of the problem?
Then what different behaviours do Wheel, Tire, and Door have?
If they behave differently, they may be subclasses of CarComponent (but not necessarily, see below). If they don't behave differently, they're just a type.
If they do behave differently, can you accomplish the same thing with Composition? Can you move the behaviours into a Strategy?
"Prefer composition over inheritance" isn't just a slogan, it's a good idea.

How to move away from Inheritance

I've searched in here and other forums and couldn't find a good answer..
I kind of know that Extending classes isn't the best of practices. And that I should use Interfaces more. my problem is that usually I start creating Interfaces and then move to Abstract classes because there's always some functionality that I want implemented on a super class so that I don't have to replicate it in every child classes.
For instance, I have a Vehicle class and the Car and Bike child classes. a lot of functionality could be implemented on the Vehicle class, such as Move() and Stop(), so what would be the best practice to keep the architecture clean, avoid code repetition and use Interfaces instead of Inheritance?
Thanks a lot!
(if you have no idea why I'm asking this you may read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html)
Inheritance ('extending classes') imposes significant limitations on class design and I'm not sure the use of interfaces as a replacement for inheritance is the best idea since it fails the DRY test.
These days, Composition is favored over Inheritance, so you might consider this post: Prefer composition over inheritance?
Interesting question. Everyone has different approaches. But it all based on personal experience and choice.
Usually, i start with an interface, then let an abstract class inherit that interface. And implement common actions there, and let others to be implemented by who ever inherits this class.
This give few advantageous based on by experience,
1.During function calls you can pass the elements as interface type or abstract class type.
2.Common variables such as ID, Names etc can be put on abstract class.
3.Easy for maintenance. For example, if you want to implement a new interface, then just implement in the abstract quickly.
If you keep in mind fundamental difference between interfaces and classes it will make it easier to decide which one to use. The difference is that interfaces represent just a protocol (usually behavioral) between objects involved, while abstract classes represent some unfinished constructions that involve some parts (data). In car example, interface is essentially a blueprint for the generic car. And abstract class would be like prefabricated specific model car body that needs to be filled with remaining parts to get final product. Interfaces don't even have to be in Java - it will not change anything - still blueprint.
Typically you would use abstract class within your specific implementation framework to provide its consumers with some basic functionality. If you just state that you never use abstract class in favor of interface - it's plain wrong from practical standpoint. What if you need 10 implementations of the same interface with 90% of the same code. Replicate code 10 times? Ok, may be you would use abstract class here but put interface on top of it. But why would you do that if you never intend to offer your class hierarchy to external consumers?
I am using word external in very wide sense - it can be just different package in your project or remote consumer.
Ultimately, many of those things are preferences and personal experiences, but I disagree with most blanket statements like extends is evil. I also prefer not to use extra classes (interfaces or abstract) unless it is required by specific parts of the design.
Just my two cents.
Inheritance allows code reuse and substitutability, but restricts polymorphism. Composition allows code reuse but not substitutability. Interfaces allow substitutability but not code reuse.
The decision of whether to use inheritance, composition, or interfaces, boils down to a few simple principles:
If one needs both code reuse and substitutability, and the restrictions imposed on polymorphism aren't too bad, use inheritance.
If one needs code reuse, but not substitutability, use composition.
If one needs substitutability, but not code reuse, or if the restrictions inheritance would impose upon polymorphism would be worse than duplicated code, use interfaces.
If one needs substitutability and code reuse, but the restrictions imposed by polymorphism would be unacceptable, use interfaces to wrap encapsulated objects.
If one needs substitutability and code reuse, and the restrictions imposed by polymorphism would not pose any immediate problem but might be problematic for future substitutable classes, derive a model base class which implements an interface, and have those classes that can derive from it do so. Avoid using variables and parameters of the class type, though--use the interface instead. If you do that, and there is a need for a substitutable class which cannot very well derive from the model base class, the new class can implement the interface without having to inherit from the base; if desired, it may implement the interface by wrapping an encapsulated instance of a derivative of the model type.
Judgment may be required in deciding whether future substitutable classes may have difficulty deriving from a base class. I tend to think approach #5 often offers the best of all worlds, though, when substitutability is required. It's often cheaper than using interfaces alone, and not much more expensive than using inheritance alone. If there is a need for future classes which are substitutable but cannot be derived from the base, it may be necessary to convert the code to use approach #5. Using approach #5 from the get-go would avoid having to refactor the code later. (Of course, if it's never necessary to substitute a class that can't derive from the base, the extra cost--slight as it may be--may end up being unnecessary).
Agree with tofutim - in your current example, move and stop on Vehicle is reasonable.
Having read the article - I think it's using powerful language to push a point... remember - inheritance is a tool to help get a job done.
But if we go with the assumption that for whatever reasons you can't / won't use the tool in this case, you can start by breaking it down into small interfaces with helper objects and/or visitors...
For example -
Vehicle types include submarine, boat, plane, car and bike. You could break it down into interfaces...
IMoveable
+ Forward()
+ Backward()
+ Left()
+ Right()
IFloatable
+ Dock()
ISink()
+ BlowAir()
IFly()
+ Takeoff()
+ Land()
And then your classes can aggregate the plethora of interfaces you've just defined.
The problem is though that you may end up duplicating some code in the car / bike class for IMoveable.Left() and IMoveable.Right(). You could factor this into a helper method and aggregate the helper... but if you follow it to its logical conclusion, you would still end up refactoring many things back into base classes.
Inheritance and Aggregation are tools... neither of which are "evil".
Hope that helps.
Do you want an answer for your specific case, or in general? In the case you described, there is nothing wrong with using an Abstract class. It doesn't make sense use an interface when all of the clients would need to implement the exact same code for Move() and Stop().
Don't believe all you read
Many times, inheritance is not bad, in fact, for data-hiding, it may be a good idea.
Basically, only use the policy of "interfaces only" when you're making a very small tree of classes, otherwise, I promise it will be a pain. Suppose you have a Person "class" (has eat() and sleep), and there are two subclasses, Mathematician (has doProblem() ) and Engineer ( buildSomething() ), then go with interfaces. If you need something like a Car class and then 56 bazillion types of cars, then go with inheritance.
IMHO.
I think, that Interfaces sometime also evil. They could be as avoidance of multiple inheritance.
But if we compare interface with abstract class, then abstract class is always more than interface. Interface is always some aspect of the class -- some viewpoint, and not whole as a class.
So I don't think you should avoid inheritance and use iterfaces everywhere -- there should be balance.

NHibernate - Single table per class hierarchy - inheriting classes are unknown

In my model all the derived classes have the same ** persistent** attributes and methods as the base abstract class. There are some class specific attributes which aren't persisted and methods have different implementation.
Right now I have about 4 inheriting classes, and I will add more in the future. The nature of the application is that such classes may be added for different uses, so its impossible to know them in advance. The only given is that they will all share the same methods and persistent attributes. The is one column which will be used as discriminator.
I am struggling with strategy. Obviously I don't want to write a ClassMap for each derived class. In fact I's like the persistence layer to be completely ignorant of these derived classes. I am thinking of having the derived classes be able to be created off the base class and to return a base class.
I don't suppose I have any better option?
Your approach is flawed in that the persistence layer can not be ignorant about the subclasses, because it needs to know what the class is when loading/storing.
What you can do is use a convention-based mapping instead of an explicit one (Fluent has Automapping, and ConfORM is convention/override based only), so you don't have to write every classmap.
In ConfORM, it's as easy as saying, for example, orm.TablePerClass<TheBaseClass>(), then mapper.CompileMappingFor(TheBaseClassAndAllItsSubclasses), and you'll get the mappings without any additional effort.

Using inheritance purely to share common functionality

I recently encountered a situation in some code I am working on that doesn't make sense to me. A set of classes are inheriting from a base class purely to share some methods in the base class. There is no method overriding, just child classes calling methods from the parent class.
It seems to me that this would be better modeled by having the child classes reference the parent class rather than inheriting from it, which I think would reduce unnecessary complexity. Is this reasonable, or am I missing some benefit of using inheritance like this?
If the parent class methods are there purely as 'utilties' then yes, I agree.
The question (for me at least), would be if the parent class could be modified in the future to have benefit. Meaning, what is the current relationship logically? If it's an "is a" between child and parent then leave it. If the parent is just a collection of methods, refactor to a utility class or use delegation.
You are correct. Unfortunately inheritance is used a lot when it is not actually needed.
If there isn't is-a relationship between the child and parent class then inheritance should not be used.
Inheritance can be used (and abused!) in different ways. Here are the three big categories.
Conceptual hierarchy:
conceptually related classes can be
organized into a specialization
hierarchy :
people, employees, managers
geometric objects ...
Polymorphism:
Objects of distinct, but related
classes may be uniformly treated by
clients
array of geometric objects
Software reuse:
Related classes may share interfaces,
data structures or behaviour.
geometric objects ...
For a complete study of the different forms of inheritance, read On the notion of inheritance.
The case that you mention, is software reuse. There is no is-a relationship, at most a has-a relationship. The goal is mostly to reuse the same code.
As you suggest, this can be refactored with delegation, or even into a utility class if the methods are essentially static.
I can suppose that the inheritance you can observe is just a result of refactoring.

Abstract classes vs interfaces to represent a family

Abstract classes are described as being useful for a family of objects (e.g. could be used for animals which are mammals). However, what difference is there between using an interface or abstract class for representing a family of related objects?
My process is to use an abstract class when I want to define common functionality but with the option for future extensions and an interface for custom functionality (implementations).
For example, I wrote an abstract class to encapsulate some database functionality which will be used heavily in a small web app at work. I wrote an abstract class with virtual methods which can be overrided with custom functionality in the future (e.g. logging, or some reporting of the database events which may be required).
Is this the right way to go? Is there any significance in choosing one construct (abstract or interface) to represent a family?
An abstract class should be used when there is common state and behavior between all types. An interface should be used when all types will have a common interface but will not share state or behavior.
Here is an example.
German Shepherd, Golden Retriever, Beagle
These three objects are all dogs, and as such they share certain common state (carnivorous, 4 legs, etc.) and they also share certain overridable behavior (bark, pant, etc.). In this instance it would make the most sense to create an abstract Dog class to hold this common state and behavior and create subtypes of Dog for each type of dog.
Pencil, Pen, Chalk
These objects have no common state and they cannot share behavior. Yet you may notice that they do have something in common - they are cabaple of writing. These objects are best build separately and without a base class and then tied together with a Writable interface that exposes each type's Write method.
I would suggest using interfaces so that you can implement new functionality in your database utility at some future point.
As always, the primary design principle when it comes to development is
Design towards an interface, not an implementation
With abstract classes, you can provide implementation that is needed and shared by all the classes in your hierarchy. Therefore, you're reusing code. You may allow the derived classes to override the default behavior or not but at least you're providing a baseline functionality like breathing for a new born animal. However, with interfaces, you can't provide any implementation. You simply define a contract that all classes that inherits that interface should honor and provide implementation for. This may lead to repetitive and duplicate code among the hierarchy of classes.
Interfaces are not very good for extensibility and you need to worry about versioning. You decide to make change to an existing interface but you will soon realize that there are a lot of classes in existence you may need to modify. Think about adding Breath method to IMammal interface that's already being used by many mammals. You will need to go and provide Breath implementation for each one. With an abstract class, you can simply add Breath method and provide some baseline implementation without having to worry about existing derived classes. So abstract classes are more flexible in term of the development of your hierarchy and the api.