Please have a look at the code below:
public class Vehicle
'Not very well designed. Contains properties and functions/subs for cars, buses, tractors, planes, drivers etc.
end class
I am wanting to refactor the code so that there is a superclass (vehicle) and many subclasses. I want to do this as I go along whilst working on much higher priorities.
If I create the new classes then there will be two Vehicle classes i.e. the refactored vehicle and the old vehicle. I believe the best approach is to create a new namespace for the refactored code e.g. company.app.businesslogiclayer.automobiles.refactoredcode, company.app.datalogiclayer.automobiles.refactoredcode. Is this the correct approach?
I think you could treat your existing clas as a subclass since it already has some class-specific functionality in it and then look at the Extract Superclass refactoring. Here you would create your new super class and then move common features from the sub class to the super class.
Refactoring for Visual Basic has a nice section on Extract Super Class that you might find interesting.
Be careful to not overuse inheritance. "Driver" strikes me as something that you really want to use composition for. A vehicle has a driver. Similarly other things such as the might be better handled using composition. For instance you could have a car that can go 200km/h, and have one that can go 300km/h. Really do not want to have different classes for that. You could have a simple int value or a EngineBehaviour class if you have something more complex. (Keyword: strategy pattern) Also be sure to not instantiate such composite objects in your object but rather inject them (keyword: dependency injection).
Related
We have used a homegrown version of object oriented coldfusion for a while and I'm just starting to experiment with cfc's and how it "should" be done...
If I understand correctly, cfinterface defines the signature of functions, and any class that implements that interface must have their own functions to do whats defined in the interface.
I'm kind of trying to do the opposite - the interface doesn't just define the function's signature, but also defines the logic of the function and anything that implements that interface can use its functions without having to define it itself. Does that exist besides creating subclasses?
For example, say you have classes A,B,C,D that all belong to the Animal class
A & B can walk
A & C can talk
B & D can sleep
Suppose the logic of walk, talk & sleep (if the object can do it) is the same regardless of the class doing it
Ideally, if A & B both implement the walking interface, they can walk without defining a separate walk method in each class.
Or borrowing a better example from this java multiple inheritance question
A Pegasus is a mix of a Horse and a Bird because it runs like a horse
but flies like a bird
Is that possible? (I think this is multiple inheritance?)
In short: no, an interface only defines a contract, it does not (and cannot) define functionality). Also CFML does not have the concept of multiple inheritance.
You will have to use single-inheritance and concrete implementations to effect what you need. I can't be bothered assessing your implementation-sharing requirements to work out what an approrpriate class hierarchy might be to minimise code duplication. I'm sure you can do that yourself (and it's not really part of your question anyhow).
One tactic you could try is to use mixins for your common methods. Store the common methods in a different library, and then inject them into your objects as required. So basically Mixins.cfc would implement walk(), talk(), sleep(), and you'd have an AFactory.cfc, BFactory.cfc, CFactory.cfc. When asking a factory for a new A, B or C, and the factory method injects the mixin methods before returning the instances. Obviously this is a fairly cumbersome process, and you'd want to use some sort of IoC container to manage all this.
A better question might come out of you showing us more real world examples... I suspect your domain design could perhaps stand improvement if you find yourself needing to do what your example suggests. Actual design requirements are seldom exposed with examples using animals.
You can do similar things with WireBox and its Virtual Inheritance feature:
http://wiki.coldbox.org/wiki/WireBox.cfm#Virtual_Inheritance
// Declare base CFC
map("BaseModel").to("model.base.BaseModel");
map("UserService").to("model.users.UserService").virtualInheritance("BaseModel");
It's basically very similar to what Adam described above; a base class is created, and references to it's public members are placed in the sub class.
https://github.com/ColdBox/coldbox-platform/blob/master/system/ioc/Builder.cfc#L535
There's no reason why you can't build something similar but you should know this has already been done.
Full disclosure, I am a contributing member of the *Box community.
I am refactoring my static library to reduce code redundancy.
I have come across a certain situation which is depicted in the below image.
In this case, is going with the Utility class the best way out, or is there some better design pattern?
Thanks for your help.
Your approach looks like a good one. It's simple.
There are other patterns, but given only the information you provided, that's exactly what I would do.
One other thing to consider would be to make class A and Class B both inherit from the same super class and then place the logic in the super class.
Or better yet, make your classes POCO model objects only with no logic, and apply the logic to the superclass using a category.
Hope that helps.
I try and abstract out any common code into a Utility or Helper class. It's neat, bug fixes will apply to both and you know that both are using exactly the same method to do the same thing.
Either extract common functionality to one superclass, or keep the superclasses as they are and reflect the common functionality in a protocol.
Deciding which solution depends on the nature of the problem, that the reflected by classes.
You can't create the utility class as you draw in your diagram because in objective C you cannot inherit from more than one superclass.
I'm relatively new in OOP.
I understand classes, methods, etc, etc but I'm having troubles with the philosophy.
Right now, I'm working on a project to manage projects, with project management, class, methods, variables, users, groups, log and task management.
So, starting with Project class, i've that:
public function create_project()
public function get_projects()
public function delete_project()
Then, ProjectClass class:
public class create_class()
public class get_classes()
public class delete_class()
But then, I though that is not the right way, so I've changed to:
Project class methods:
set_name, get_name (and similar methods)
add_class
get_classes
add_log
get_logs
ProjectClass class methods:
set_project_id (and get)
add_variables (and get)
add_method
...
So, in the first case, is the Project class who create new projects, the ProjectClass class who creates the clases and the Method class who creates the methods, and in the second case, is the Project class who creates and manages its classes and is the ProjectClass class who creates and manages its methods.
So, is any of theses "styles" correct?
If is the second case the correct case, who creates the projects? Itself?
Thank you so much
In the general case it is really hard to tell if a design is better than the other if you don't have clear responsibilities to assign (and by this I mean behavior outside from getters and setters). As time went by I moved away from upfront design to a iterative/incremental one, tackling one problem at a time and refactoring the design as needed. In this case I would try to lay down the basic requirements of your system and start a design-implementation cycle for each of them, re-structuring your model as you go tackling new requirements.
Just an an example consider this question: Does it make sense to have a class that is not bounded to a project? If the answer is no then it can be a good idea to have a method like Project>>createClass(aClassName), since you are explicitly stating that a class is created in the context of a project. Also you can make the proper connections between a class and the project it belongs to inside the method's implementation. However it is also a valid approach to define a constructor in the ProjectClass class that takes a project as a parameter. In that way you are saying "if you want to create a new class, then you must provide the project where it belongs to". Which approach to use depends on many things, one of them being programmer tastes :), so it is really hard to state if one is better than the other without having a specific context to evaluate them.
Finally, if it helps, there are a few things that are worth mentioning:
Assuming that public function create_project() is an instance method, why does an instance of a Project know how to create other projects? At first it doesn't make much sense, since that is basically a class-side responsibility, unless you have a specific motivation for this (e.g. like the Prototype pattern).
Why does a project answer to get_projects()? Are they related in some way? Or it just list all the projects? Then again, this sounds like a class-side responsibility.
I generally don't like to add the concept that the message receiver represents as part of the message. So, I wouldn't call the message delete_project(), since it is redundant to state $project->delete_project() (you already know the receiver of the message is a project).
You should be consistent with your class names. If you use ProjectClass to represent classes then you should use ProjectMethod to represents methods (though I personally don't like these names, IMHO they are misleading). It is quite important to chose proper names and keep them consistent in your domain model.
HTH
I have common functions, such as syntactic sugar for calling the database, logging or site-wide information such as a look-up tables.
If I put these in a site-wide base class I will have access to them, however it just seems intuitively wrong to use a parent class this way. It would make more sense to use the base class as a 'has a' relationship rather than an 'is a'.
Or perhaps this is good design? Is there any problem doing this?
Parent classes should instantiate some base functionality and a child should instantiate the differentiating code.
IMNSHO, what you are describing is a bastardization of that process.
Ideally you would only want to serializable POCO classes, because they only contain properties and no methods.
Having a baseclass for common functionality might be a good idea, if you place code it in, that will be same in every childpage and if there is no other good place.
For instance you could place Helper-methods inside a baseclass, but that breaks OOP in my opinion.
In my opinion, having a class that derives from System.Web.UI.Page and replaces some logic in the OnInit event or other events is a very good strategy. I've used this approach in various projects, but I limited the code in the baseblass to globalization and logic for memberpages (like redirects to non public pages).
I believe that what you are doing is wrong.
First of all, object should be dedicated to one task. Having db connection handling, logging or look-up tables in the same class seems very ugly, regardless of whether these funcitonalities are inherited or not.
Moreover, the functionalities you described seem like fitting the exact idea of an object, just as described above. So, to answer your question: yes, has-a relationship seems like a much better solution.
In general, I tend to try to put program-wide accessible functions in separate classes. If possible, I try to use static methods. Behind these sometimes are singletons, sometimes there is some kind of queue, and sometimes something entirely different. Still, having one single point of origin for such functionalities the code is very flexible. If static methods are not applicable, especially when there is a need to store some information in such helper class, only then do I instantiate an object for each instance of other class. Even then factory/pool single point of origin static methods are often a good idea.
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.