ActiveJDBC Object with Multiple Parents that reference the same Class - activejdbc

I have a fairly simple model with two objects: Team and Game. The Team object has the name of the team, and the Game object looks-up to the Team object twice. One through the "away_team_id" and one through the "home_team_id" field.
Game ----home_team_id----> Team
|
+------away_team_id----> Team
I'm fairly new to ActiveJDBC, but have used PHP ActiveRecord for quite some time. I cannot for the life of me figure out how to reference each team through the Game object. I do have these annotations in my Game object:
#BelongsToParents({
#BelongsTo(foreignKeyName="home_team_id",parent=Team.class),
#BelongsTo(foreignKeyName="away_team_id",parent=Team.class)
})
public class Game extends Model {
}
In my test code, I have:
Team homeTeam = game.parent (Team.class);
But obviously that's only one of them, and I'm not even sure how it figures out which one it is! Any help would be greatly appreciated.
Thanks in advance!

This is an unusual case. I would suggest something like this:
public class Game extends Model{
public Team getHomeTeam(){
return Team.findFirst("id = ?", get("home_team_id"));
}
public Team getAwayTeam(){
return Team.findFirst("id = ?", get("home_away_id"));
}
}
I would suggest wrapping ActiveJDBC in semantic methods like this to help potential refactoring in the future.
tx

Related

NullObject Pattern: How to handle fields?

Suppose we have Book class which contains year_published public field. If I want to implement NullObject design pattern, I will need to define NullBook class which behaves same as Book but does not do anything.
Question is, what should be the behavior of NullBook when it's fields are being assigned?
Book book = find_book(id_value); //this method returns a NullBook instance because it cannot find the book
book.year_published = 2016; //What should we do here?!
The first thing you should do is to make your properties private.
class NullBook {
private year_published;
// OR solution2 private year_published = null;
public setYearPublished(year_published) {
this.year_published = null;
// OR solution2 do nothing!
}
}
You can also define the field private in the parent class, so the children will have to implement the setter to acces the field
class Book {
private year_published;
public setYearPublished(year_published) {
this.year_published = year_published;
}
}
class NullBook extends Book {
public setYearPublished(year_published) {
parent::setYearPublished(null);
}
}
Why use getters and setters?
https://stackoverflow.com/a/1568230/2377164
Thing is: patterns are about balancing. Yes, it is in general good practice to not return null, but to having else to return; but well: what is returned should still make sense!
And to a certain degree, I don't see how having a "NullBook" really helps with the design of your application. Especially as you allow access to various internal fields. You exactly asked the correct question: what should be the published year, or author, or ... of such a "NullBook"?!
What happens for example when some piece of code does a "lookup" on books from different "sources"; and then tries to sort those books on the published year. You sure don't want your NullBook to ever be part of such data.
Thus I fail to see the value in having this class, to the contrary: I see it creating a potential for "interesting" bugs; thus my answer is: step back and re-consider if you really need that class.
There are alternatives to null-replacing objects: maybe your language allows for Optionals; or, you rework those methods that could return null ... to return a collection/array of books; and in doubt: that list/array is simply empty.
Long story short: allowing other classes direct access to private fields is a much more of an import design smell; so you shouldn't be too focused on NullObjects, while giving up on such essential things as Information Hiding so easily on the other hand.

Is it bad OOP practice to subclass MANY classes from a base class?

I'm relatively new to this site so if I am doing something wrong when it comes to posting questions and whatnot please let me know so I can fix it for next time.
I'm curious as to whether or not it is bad OOP practice to subclass multiple classes from a single base class. That probably doesn't quite make sense so I'm going to elaborate a little bit.
Say for instance you are designing a game and you have several different monsters you might come across. The approach I would take is to have a base abstract class for just a general monster object and then subclass all of the specific types of monsters from the base class using a new class.
One of my instructors told me that you shouldn't rely on inheritance in this case because the number of monsters will continue to grow and grow and the number of classes will increase to a point where it is hard to keep track of all of them and thus yo will have to recompile the program with every new class added in the future.
I don't understand why (or even if) that's a bad thing. If anybody could help me understand where my professor is coming from that would be much appreciated.
Thanks!
If monsters are very similar, in that the only differences are (for example) their name, how much damage they impart, what color they are, etc., then these differences which can be reflected in a field (in values), may make sub-classing unnecessary.
If, however, you have monsters that are fundamentally different from others, such that it is necessary to have very different methods and logic, and more specifically, differences that cannot be reflected in fields, then a sub-class SpecialMonster may be necessary.
But again, even SpecialMonster may not need to be sub-classed by individual monster types, as it's fields may be enough to distinguish between them.
While it's legal to have a million sub-classes of specific monster types, you don't want to take care of all that duplicate code when it could simply be expressed in the fields of new Monster instances, such as
new Monster("Goob", WakeTime.NOCTURNAL, 35, new Weapon[]{sword, hammer, knittingNeedle});
new Monster("Mister Mxyzptlk", WakeTime.ANYTIME, 71, new Weapon[]{sword, mindMeld, cardboardCutter});
There is an alternative, where you do have a lot of classes, but you don't impose them onto your users, and you don't clutter up your API/JavaDoc with them. If your Monster happens to be an abstract class
public abstract class Monster {
private final String name;
...
public Monster(String name, int default_damage, WakeTime wake_time, Weapon[] weapons) {
this.name = name;
...
}
public String getName() {
return name;
}
...
public abstract int getDamage(int hit_strength);
}
Then you could have a Monster convenience creator like this:
/**
<P>Convenience functions for creating new monsters of a specific type.</P>
**/
public class NewMonsterOfType {
private NewMonsterOfType() {
throw new IllegalStateException("Do not instantiate.");
}
/**
<P>Creates a new monster that is nocturnal, has 35-default-damage, and whose weapens are: sword, hammer, knittingNeedle.</P>
**/
public static final GOOB = new GoobMonster();
/**
<P>Creates a new monster that can be awake at any time, has 71-default-damage, and whose weapens are: sword, mindMeld, cardboardCutter.</P>
**/
public static final MISTER_MXYZPTLK = new MisterMxyzptlkMonster();
}
class GoobMonster extends Monster {
public GoobMonster() {
super("Goob", WakeTime.NOCTURNAL, 35, new Weapon[]{sword, hammer, knittingNeedle});
}
public int getDamage(int hit_strength) {
return (hit_strength < 70) ? getDefaultDamage() : (getDefaultDamage() * 2);
}
}
class MisterMxyzptlkMonster extends Monster {
public GoobMonster() {
super("Mister Mxyzptlk", WakeTime.ANYTIME, 71, new Weapon[]{sword, mindMeld, cardboardCutter});
}
public int getDamage(int hit_strength) {
return (hit_strength < 160) ? getDefaultDamage() + 10 : (getDefaultDamage() * 3);
}
}
In order for these private (actually package-protected) classes to not show up in you JavaDoc, you need to set its access to something either protected or public.
Inheritance is quite natural in your scenario as all the specific monsters ARE base monsters as well :). I'd actually use inheritance a lot here, since probably specific monsters do have specific behaviour that would have to be overriden. MonsterA might move by crawling while MonsterB might move by flying. The base AMonster would have an abstract Move() method , implemented by those sub types.
This isn't a final answer, it really much depends on the game needs, however, in simplified form, inheritance makes sense here. The number of monster types might continue to grow, but really, are they all the same? The monster design is just based on grouping together some predefined data/behaviour? The game is quite trivial then...
I really get the impression your instructor doesn't code games for a living (me neither, although I did make a game some time ago), but his explanation why you shouldn't use inheritance is way too simplified. The number of defined classes is never an issue in an app, the more the better IF the Single Responsibility Principle is respected.
About you have to recompile your app.... yeah, when you fix a bug you have to recompile it too. IMO, the reasons he gave to you aren't valid for this scenario. He needs to come up with much better arguments.
In the mean time, go for inheritance.
Theoretical question needs theoretical answer :).
It is not just bad, it is pointless. You should have a LIMITED number of "base" classes that inherits from other classes, and those classes should be composed from other classes (vide favour composition versus inheritance).
So as complexity grows the number of classes that base classes are composed from should grows. Not number of base classes itself.
It is like in the industry. If you see machines for instance, they are really composed from large quantity of small parts, and some of those small parts are the same in different machines. When yo designing new machine you do not order new unique "base" part for it just to have a name for your new machine. You use parts existing on a market and you designing some new parts (not "base") only if you cannot find existing counterparts...

OOP where to put orphan methods

Apologies if this has been answered elsewhere, my search didn't yield quite the answer I was looking for.
Hypothetically speaking, let us say I am building an application for a bookshop.
I have a class that handles all my database transactions. I also have a 'Book' class which extends the Database class, calling the Database constructor from it's own constructor, removing the need to instantiate the Database class first:
class Book extends Database {
__construct($book_id){
parent::__construct();
$this->databaseGet("SELECT * FROM..."); // method in Database class
etc...
}
}
I can pass a reference id to the 'Book' class constructor and create an object containing information pulled from the database about that book along with several methods relevant to a given book.
But I also want to list all the books in the database. My question is, where do I put this method and other methods that simply don't have a context such as 'Book'?
I could create a single "GetStuff" or 'Bookshop' class that extends the Database class, which would contain all these single-use methods. But that requires it to be loaded all the time as these orphan methods would be used all over the program.
I could create lots of classes that house a single method but that would require instantiating the class to an object in order to call the method, seems like overkill.
They aren't general utilities, they have a place in the business model. Just where should I put these orphan methods?
If I understand it, you're asking where should code go that relates to a specific type but doesn't implement a behaviour of the type itself. There is no single answer. According to the overall design of the system, it could be part of the type - Smalltalk classes have 'class fields' and 'instance fields', and there is nothing wrong with that - or it could end up anywhere it makes sense. If it relates to something external to the type itself - that is, it's not merely a matter of not being the behaviour of an instance, but a matter of being an interaction with something extraneous - it may make sense to put it outside. For instance, you may have Book, BookDatabase, BookForm, BookWebService, etc. There's no harm in some of those classes having few members, you never know when you'll want to add some more.
Book is a book, Books is collection of books.
Database is one thing you could use to persist a lot of books so you don't have to type them all in again.
It could be an xml file, an excel spreadsheet, even a webservice.
So write Book and Books, then write something like
BookDatabase extends database with methods like
Books GetBooks();
and
void SaveBook(Book argBook);
The real trick is to make Book and Books work no matter what / how they are stored.
There's lot more to learn around that, but first thing to do is start again and not make your data objects dependant on a particular "database".
Seems your design is seriously flawed. You have to separate three concerns:
Your Domain Layer (DM): In this case, Book belongs to it.
Data Access Layer (DAL): Handles database storage. Domain Layer does not know about this layer at all.
Service Layer (SL): handles use cases. A use case may involve multiple object from Domain, as well as calls to DAL to save or retrieve data. Methods in service layer perform a unit of work.
A simplified example:
// Model Object
class Book {
title;
author:
isbn;
constructor(title, author, isbn) {// ...}
// other methods ...
}
// DAL class
class BookDataMapper {
// constructors ...
save(Book book) {}
Book getById(id) {
String query = get from book table where book_id = id;
execute query;
parse the result;
Book book = new Book(parsed result);
return book;
}
Book getByTitle(title) {}
...
getAll(){} // returns all books
}
//Service class
class BookService {
BookDataMapper bookMapper;
buyBook(title) {
// check user account
// check if book is available
Book book = bookMapper.getBytitle(title);
if book available
charge customer
send the book to ship etc.
}
}

Could someone please explain OOP using SPORT examples?

Im new to OOP concepts (Abstraction, Encapsulation, Inheritance and Polymorphism).
Could someone please explain OOP using a SPORTS example such as Sport which can have subclasses (Football, Rugby, Cricket, Boxing, snooker, etc).
Also what would be the basic structure for a Athlete Management System.
Any help would be greatly appreciated.
Many thanks.
This is a pretty generic question, and not easy to answer precisely, but here are a few pointers, which should hopefully give you some ideas about Inheritance and Polymorphism at least.
All sports (the concepts) are in fact, instances of Sport (the class). This means that the classes Football, Boxing, etc, all inherit from the class Sport.
Things that can be done in Sport, can be done in any subclass of Sport, since it is in fact, a sport. For instance, if Cheer(), Score(), and win() are defined as methods in Sport, then each of the sub-classes can also perform these - that is inheritance!
Each sport may however, have different ways of scoring. If so, they can override the method from Sport, and provide their own logic for this. They must, however, still comply with the definition of the method Score() set down in Sport, for them to be able to behave as a Sport. This is polymorphism!
Cheering and winning may be the same concept in all sports, so they can just be inherited from Sport
A simple pseudo code example. This may be pretty stupid (and maybe not even technically correct in sports terms, but I hope you get the point! :))
public class Sport{
public function score(){
print("Scored!");
}
public function Win(){
print("Won!");
}
public function Cheer(){
print("Cheeeeeeeeer!!!");
}
}
public class Soccer Inherits Sport{
public override function score(){
print("One goal!");
}
}
public class Boxing Inherits Sport{
public override function score(){
print("Knockout!");
}
}
// Using the classes:
Sport generalSport = new Sport(); // generalSport is just a non-specific sport
Sport soccerSport = new Soccer(); // soccerSport is a Soccer, but also a Sport!
Sport boxingSport = new Boxing(); // boxingSport is a Boxing, but also a Sport!
generalSport.Win(); // This should output: "Won!" (from Sport)
soccerSport.Win(); // ... "Cheeeeeeeeer!!!" (inherited from Sport)
boxingSport.Cheer() // ... "Cheeeeeeeeer!!!" (inherited from Sport)
generalSport.score(); // "Scored!"
soccerSport.score(); // "One Goal", since it was overridden in Soccer
boxingSport.score() // "Knockout!", since overridden in Boxing
Hint: Just think of what things "are" in real life. If X inherits Y, X may be defined as an X specifically, but it is still a Y too, and can be treated as such (only with the possibility of adding a few extra properties).

Inheritance vs enum properties in the domain model

I had a discussion at work regarding "Inheritance in domain model is complicating developers life". I'm an OO programmer so I started to look for arguments that having inheritance in domain model will ease the developer life actually instead of having switches all over the place.
What I would like to see is this :
class Animal {
}
class Cat : Animal {
}
class Dog : Animal {
}
What the other colleague is saying is :
public enum AnimalType {
Unknown,
Cat,
Dog
}
public class Animal {
public AnimalType Type { get; set; }
}
How do I convince him (links are WELCOME ) that a class hierarchy would be better than having a enum property for this kind of situations?
Thanks!
Here is how I reason about it:
Only use inheritance if the role/type will never change.
e.g.
using inheritance for things like:
Fireman <- Employee <- Person is wrong.
as soon as Freddy the fireman changes job or becomes unemployed, you have to kill him and recreate a new object of the new type with all of the old relations attached to it.
So the naive solution to the above problem would be to give a JobTitle enum property to the person class.
This can be enough in some scenarios, e.g. if you don't need very complex behaviors associated with the role/type.
The more correct way would be to give the person class a list of roles.
Each role represents e.g an employment with a time span.
e.g.
freddy.Roles.Add(new Employement( employmentDate, jobTitle ));
or if that is overkill:
freddy.CurrentEmployment = new Employement( employmentDate, jobTitle );
This way , Freddy can become a developer w/o we having to kill him first.
However, all my ramblings still haven't answered if you should use an enum or type hierarchy for the jobtitle.
In pure in mem OO I'd say that it's more correct to use inheritance for the jobtitles here.
But if you are doing O/R mapping you might end up with a bit overcomplex data model behind the scenes if the mapper tries to map each sub type to a new table.
So in such cases, I often go for the enum approach if there is no real/complex behavior associated with the types.
I can live with a "if type == JobTitles.Fireman ..." if the usage is limited and it makes things easer or less complex.
e.g. the Entity Framework 4 designer for .NET can only map each sub type to a new table. and you might get an ugly model or alot of joins when you query your database w/o any real benefit.
However I do use inheritance if the type/role is static.
e.g. for Products.
you might have CD <- Product and Book <- Product.
Inheritance wins here because in this case you most likely have different state associated with the types.
CD might have a number of tracks property while a book might have number of pages property.
So in short, it depends ;-)
Also, at the end of the day you will most likely end up with a lot of switch statements either way.
Let's say you want to edit a "Product" , even if you use inheritance, you will probably have code like this:
if (product is Book)
Response.Redicted("~/EditBook.aspx?id" + product.id);
Because encoding the edit book url in the entity class would be plain ugly since it would force your business entites to know about your site structure etc.
Having an enum is like throwing a party for all those Open/Closed Principle is for suckers people.
It invites you to check if an animal is of a certain type and then apply custom logic for each type. And that can render horrible code, which makes it hard to continue building on your system.
Why?
Doing "if this type, do this, else do that" prevents good code.
Any time you introduce a new type, all those ifs get invalid if the new type is not handled. In larger systems, it's hard to find all those ifs, which will lead to bugs eventually.
A much better approach is to use small, well-defined feature interfaces (Interface segregation principle).
Then you will only have an if but no 'else' since all concretes can implement a specific feature.
Compare
if (animal is ICanFly flyer)
flyer.Sail();
to
// A bird and a fly are fundamentally different implementations
// but both can fly.
if (animal is Bird b)
b.Sail();
else if (animal is Fly f)
b.Sail();
See? the former one needs to be checked once while the latter has to be checked for every animal that can fly.
Enums are good when:
The set of values is fixed and never or very rarely changes.
You want to be able to represent a union of values (i.e. combining flags).
You don't need to attach other state to each value. (Java doesn't have this limitation.)
If you could solve your problem with a number, an enum is likely a good fit and more type safe. If you need any more flexibility than the above, then enums are likely not the right answer. Using polymorphic classes, you can:
Statically ensure that all type-specific behavior is handled. For example, if you need all animals to be able to Bark(), making Animal classes with an abstract Bark() method will let the compiler check for you that each subclass implements it. If you use an enum and a big switch, it won't ensure that you've handled every case.
You can add new cases (types of animals in your example). This can be done across source files, and even across package boundaries. With an enum, once you've declared it, it's frozen. Open-ended extension is one of the primary strengths of OOP.
It's important to note that your colleague's example is not in direct opposition to yours. If he wants an animal's type to be an exposed property (which is useful for some things), you can still do that without using an enum, using the type object pattern:
public abstract class AnimalType {
public static AnimalType Unknown { get; private set; }
public static AnimalType Cat { get; private set; }
public static AnimalType Dog { get; private set; }
static AnimalType() {
Unknown = new AnimalType("Unknown");
Cat = new AnimalType("Cat");
Dog = new AnimalType("Dog");
}
}
public class Animal {
public AnimalType Type { get; set; }
}
This gives you the convenience of an enum: you can do AnimalType.Cat and you can get the type of an animal. But it also gives you the flexibility of classes: you can add fields to AnimalType to store additional data with each type, add virtual methods, etc. More importantly, you can define new animal types by just creating new instances of AnimalType.
I'd urge you to reconsider: in an anemic domain model (per the comments above), cats don't behave differently than dogs, so there's no polymorphism. An animal's type really is just an attribute. It's hard to see what inheritance buys you there.
Most importantly OOPS means modeling reality. Inheritance gives you the opportunity to say Cat is an animal. Animal should not know if its a cat now shout it and then decide that it is suppose to Meow and not Bark, Encapsulation gets defeated there. Less code as now you do not have to do If else as you said.
Both solutions are right.
You should look which techniques applies better to you problem.
If your program uses few different objects, and doesn't add new classes, its better to stay with enumerations.
But if you program uses a lot of different objects (different classes), and may add new classes, in the future, better try the inheritance way.