I am making sims like game and right now I am trying to figure out how I will structure my objects.
Right now I am thinking to create a class called GameObject, the psuedo is below
public class GameObject {
name:String
width:int
height:int
}
This way I could create objects like bushes, trees, and buildings. But then I began to think. what if I wanted to create multiple buildings and trees of the same type ?? I would have to keep making instances of GameObject and giving it a new name and height and width. The properties would have to be the same values in order for me to duplicate one object. That seems a little tedious. Then I figure , maybe that isnt the right way to go. So I was thinking, I would have to extend GameObject like below
public class Tree extends GameObject{
birdHouse:Boolean
}
public class Building extends GameObject{
packingGarage:Boolean
stories:Number
}
public class House extends GameObject{
garage:Boolean
stories:Number
}
Now this way, I can just create multiple instances of house, or tree, without creating properties that specify that it is indeed a house or tree. This seems more logical, but at the same time it seems it allocates more memory because I am creating more classes.
I just need to know what the best practices for dealing with objects like this. If anyone can help me out with this. also if you know any resources for best practices of reducing loading on games or any application at that. I also want to use Interfaces. the second concept seems more reasonable and I was thinking about having the parent implement a interface like below
public class GameObject implement IGameObject {
name:String
width:int
height:int
}
Now this way I can create a class that has a method that loosely accept accepts any type that inherits GameObject.
Selector.loadObject(gObject:IGameObject);
Depending on what type it is (i.e tree, building, house) I can use a case statement to figure out which type it is and evaluate it accordingly.
I also created a Tile Class that will pass through the loadObject method. It also will be a child of the GameOject class. if the case statement finds that it is type Tile, it will highlight whatever Tile depending on what tile my mouse is over.
My second question is if a class inherits a class that implements a interface, is that class child class considered to be a IGameObject as well. or does it have to implement that interface directly.
does all this sound like I am going in the right directions lol, as far as organization is concerned.
Thanks for all of your help, thanks guys!
One thing you could think about is using Composition of objects over inheritance. This sort of goes along with the Flyweight answer. Rather than having all your GameObjects inherit properties from GameObject; instead, have each game object just have a reference or pointer to an object or interface that has the properties it needs. For example, all your game objects probably have some sort of "size" property - rather than inheriting this from a base class, just have each game object reference or point to a "Size" class, so that the size object can potentially be shared among similar objects.
You should look into the Flyweight pattern
From wikipedia:
Flyweight is a software design
pattern. A flyweight is an object that
minimizes memory use by sharing as
much data as possible with other
similar objects; it is a way to use
objects in large numbers when a simple
repeated representation would use an
unacceptable amount of memory.
As for your second question, the answer is yes. All Subclasses of a Class can be said to implement all interfaces that the parent class implements.
This seems more logical, but at the
same time it seems it allocates more
memory because I am creating more
classes.
Creating new classes doesn't use a significant amount of memory. It's creating instances that uses memory - but again, the amount will be negligible compared to the memory used by loading in your graphics etc. Don't worry about memory. Your only concern at this stage should be good code organisation.
You should have separate classes when they have different behaviour. If they have the same behaviour but different properties, then you use the same class and set the properties accordingly.
In this case, you don't appear to have significantly different behaviour, but if separating it into Tree, Building, and House makes life easier for you when managing which items can be included in others etc, do it.
Related
I'm learning C# and trying to do simple object oriented exercise.
I have three weapon classes, "Bow,dagger,Spear", so I made one interface and inherited from this interface IWeapon.
Now user must choose one of the weapon, so I want to make Collection of weapons and I'm trying to make list of IWeapons, is it correct way? Isn't it bad practice to make list type of IWeapon ? Because of, I know that Interfaces are like a contracts, and I think it's a bad idea to make List with Interface type. One way is to change interface to an abstract class, but I want to use Interface.
private static List<IWeapon> weapons = new List<IWeapon>();
Is it correct way or not ?
The only problem with your solution is that static members should be thread-safe. It's like a convention among C# developers. So either change it to a non-static and, preferrably, readonly:
private readonly List<IWeapon> weapons = new List<IWeapon>();
Or use a thread-safe collection:
private static ConcurrentBag<IWeapon> weapons = new ConcurrentBag<IWeapon>();
I have two thoughts on this:
I can easily imagine a situation where one would want to use a collection of a particular interface. For example, if you were writing a download queue. You would have weapons and shields and players and villages which all implement an IDownloadableThing interface. Your queue code would have a collection of IDownloadableThings because it doesn't care what its actually downloading, it just cares that that thing know what its URL or file path or whatever is.
I'm a little wary of developer edicts. There are good ideas and traps you should be aware of in any language, but context can change everything. When you are trying to figure out if 'Weapon' should be an abstract class, ask yourself a couple things. Should a class implementing Weapon also be allowed to be a Shield? If locking down multiple inheritance is important, then abstract classes are the way to do that. Will there be a lot or any common behavior that classes implementing 'Weapon' will want to share? For example, is there a CalculateDamage() method that's basically identical between all 'Weapon' implementations. Once you have answers to what a class of interface's purpose is, then it'll be easier to choose to violate a development guideline because the situation requires it or re-think your approach.
There's nothing wrong with using interfaces as values for lists.
However, this may not be appropriate to your specific case. You said you'd like the player to pick from a list of weapons. Now consider the follwing scenarios:
You have a single player in your game, and he chose a single weapon. You have created a whole list worth of weapon instances that no one will ever need or use. This just wastes memory.
You have multiple players in the game, and they both choose the same weapon. This could be even worse. If you assign the weapons like this: player.Weapon = weapons[1], then both players will have the same instance of the weapon. If one user assings buffs to his weapons, or maybe if the weapon degrades or breaks, both the players weapons will be affected, since it is, in fact, the same weapon. Think of it like this, both you and I would like a chocolate cake. The store can either give us both the same piece of cake, in this case, if you eat it, I will have none. Or they can bake us both new cakes, so each of us can have his own.
The appropriate solution in this case is to save the types of weapons and present these to the player. Then create a new weapon instance according to the player's choice.
There are several different ways to do this, the simplest of which is to create an enum with the weapon types and present these to the player.
So instead of the list, you can have:
public enum WeaponType
{
Bow,
Dagger,
Spear
}
And now you need to create the instance of the weapon the player chose:
public IWeapon CreateWeapon(WeaponType weaponType)
{
switch(weaponType)
{
case WeaponType.Bow:
// Create Bow...
case WeaponType.Dagger:
// Create Dagger...
case WeaponType.Spear:
// Create Spear...
}
}
This is the basis to the Factory design pattern. I would highly recommend you to take a look at it. Here's a good place to start: http://www.dofactory.com/net/factory-method-design-pattern
I have very long class inheritance hierarchy. For example:
-MyAbstractObject
--MyAbstractUiObject
---MyAbstractTable
-----MyAbstractPageableTable
-------MyAbstractScrollableTable
---------MyAbstractStateblaTable
etc...
I read at Code complete that ideal inheritance deep is 3. And sometimes it allowable to make inheritance deep 7-9. But I have inheritance deep 11!
How I can change my architecture? What design pattern is applicable to my case? And what is bad is that I can change places of MyAbstractPageableTable and MyAbstractScrollableTable in inheritance hierarchy. This 2 classes not mixed into one because my goal is single responsibility. Also I want to provide for users different interfaces (APIs)
Often it is better to use a Strategy-Pattern and not create an Subclass for each use case. But it is hard to give any hard advice because it depends on the circumstances.
In your example I would guess you could do a Table Implementation and give it an strategy-object that handles for example the Pagenation or any other display strategy the table should support.
According to Joshua Bloch's "Effective Java" it is often better to use composition over inheritence. I don't think larger inheritence depths are bad, as long as they stay understandable, with 11 levels I would guess thats not the case.
Composition. You get two smaller inheritance hierarchies:
class MyAbstractObject
class MyAbstractUIObject : MyAbstractObject
class MyAbstractTable : MyAbstractUIObject
interface IMyAbstractTableBehaviour { void Perform(); }
class MyAbstractTablePageableBehaviour : IMyAbstractTableBehaviour
class MyAbstractTableScrollableBehaviour : IMyAbstractTableBehaviour
class MyAbstractTableStateableBehaviour : IMyAbstractTableBehaviour
You can instantiate a subclass of MyAbstractTable with any combination of the three behaviours, and implementing additional behaviours is trivial.
I don't know what code complete is but the ideal inheritance is probably just a signal in the right direction (guidance), it doesn't apply to every situation (maybe your case is one of them). The inheritance hierarchy for UI controls usually has this phenomenon such as Controls in WPF (Windows Presentation Foundation). So if you're building a UI framework you may encounter this. It Depends on the Context (Your Specific Situation), but overall inheritance increase coupling in your code and as #Casey said you should favor Composition if that is possible.
Without more details in the question, it's hard to give a specific answer.
With UI frameworks (which your class seems to be a part of) you do tend to have deeper than average inheritance hierarchies. The classes at the top tend to deal with layout and such, so you get several deep before you get to add your rendering and custom behavior classes.
But, are there any classes that you could change? For instance, does it really make sense for ScrollableTable to derive from PageableTable, or could you make interfaces IScrollableTable and IPageableTable?
i am building a sort of program that generates a random list of word according to a database.
I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)
I have 3 variables that indicate the last 3 words chosen.
how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)
To make myself clearer:
accualy what I need is to know how to keep track of a variable between multiple classes.
I might be using the whole classes thing wrong... I am now triyng to get the grasp of it.
Thank you very much,
Barak.
Your two options as I see it are:
1) an instance of a class that holds those variables that can be passed around
You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.
2) A static class with static members holding this information.
It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.
Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)
I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.
Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.
Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.
If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.
Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.
Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.
I also agree that your post should be improved with snippets of actual code - help us helping you.
And I hope your code is not being used to generate spam mails/posts... :-)
When i try to create good object hierarchy which will help to write less code and avoid to use unnecessary fields ,i feel myself free to create many base classes for good grouping which is usually abstract.
What can be disadvantage of doing it like that ? Many times inherited class can be slower ?
To see many unnecessary abstract classes which hasn't enough good naming can cause confusing when encounter it in intelli-sense(auto-complete) ? What can be other else ?
Many times inherited class can be slower?
There's only one way to answer performance questions: try it both ways, and measure the results. Then you'll know.
What can be disadvantage of doing it like that?
The disadvantage of overly complex object hierarchies are:
1) they are confusing because they represent concepts that are not in the business domain
For example, you might want to have a storage system that can store information about employees, computers and conference rooms. So you have classes StorableObject, Employee, Room, Computer, where Employee, Room and Computer inherit from StorableObject. You mean "StorableObject" to represent something about your implementation of your database. Someone naively reading your code would ask "Why is a person a "storable object?" Surely a Computer is a storable object, and a Room is where it is stored. When you mix up the mechanisms of the shared code with the meaning of the "is a kind of" relationship in the business domain, things get confusing.
2) you only get one "inheritance pivot" in C#; it's a single inheritance language. When you make a choice to use inheritance for one thing, that means you've chosen to NOT use inheritance for something else. If you make a base class Vehicle, and derived classes MilitaryVehicle and CivilianVehicle, then you have just chosen to not have a base class Aircraft, because an aircraft can be either civilian or military.
You've got to choose your inheritance pivot very carefully; you only have one chance to get it right. The more complicated your code sharing mechanism is, the more likely you are to paint yourself into a corner where you're stuck with a bunch of code shared, but cannot use inheritance to represent concepts that you want to model.
There are lots of ways to share code without inheritance. Try to save the inheritance mechanism for things that really need it.
I have just made a very simple practical test (unscientific though) where I created empty classes named A, B, C ... Q, where B inherited from A, C from B and so on to Q inheriting from P.
When attempting to retrieve some metrics on this I created some loops in which I simply created x number of A object, x number of B objects and so on.
These classes where empty and contained only the default constructor.
Based on this I could see that if it took 1 second (scaled) to create an object of type A then it took 7-8 seconds to create an object of type Q.
So the answer must be YES a too deep hierarchy will impact performance. If it is noticable depends on many things though, and how many objects you are creating.
Consider composition over inheritance, but I don't think you'll experience performance issues with this.
Unless you're doing reflection, or something like that where your code has to walk the inheritance tree at runtime, you shouldn't see any speed differences, no matter how many levels of inheritance a class has, or no matter how many classes implement your particular class.
The biggest drawback is going to be making your code unnecessarily brittle.
If class B is implementing/inheriting A just because B is going to need similar fields, you will find yourself in a world of hurt six months later when you decide that they need to behave differently from A to B. To that regard, I'll echo k_b in suggesting you'll want to look at the Composition pattern.
I am running into a design disagreement with a co-worker and would like people's opinion on object constructor design. In brief, which object construction method would you prefer and why?
public class myClass
{
Application m_App;
public myClass(ApplicationObject app)
{
m_App = app;
}
public method DoSomething
{
m_App.Method1();
m_App.Object.Method();
}
}
Or
public class myClass
{
Object m_someObject;
Object2 m_someOtherObject;
public myClass(Object instance, Object2 instance2)
{
m_someObject = instance;
m_someOtherObject = instance2;
}
public method DoSomething
{
m_someObject.Method();
m_someOtherObject.Method();
}
}
The back story is that I ran into what appears to be a fundamentally different view on constructing objects today. Currently, objects are constructed using an Application class which contains all of the current settings for the application (Event log destination, database strings, etc...) So the constructor for every object looks like:
public Object(Application)
Many classes hold the reference to this Application class individually. Inside each class, the values of the application are referenced as needed. E.g.
Application.ConfigurationStrings.String1 or Application.ConfigSettings.EventLog.Destination
Initially I thought you could use both methods. The problem is that in the bottom of the call stack you call the parameterized constructor then, higher up the stack, when the new object expects a reference to the application object to be there, we ran into a lot of null reference errors and saw the design flaw.
My feeling on using an application object to set every class is that it breaks encapsulation of each object and allows the Application class to become a god class which holds information for everything. I run into problems when thinking of the downsides to this method.
I wanted to change the objects constructor to accept only the arguments it needs so that public object(Application) would change to public object(classmember1, classmember2 etc...). I feel currently that this makes it more testable, isolates change, and doesn't obfuscate the necessary parameters to pass.
Currently, another programmer does not see the difference and I am having trouble finding examples or good reasons to change the design, and saying it's my instinct and just goes against the OO principles I know is not a compelling argument. Am I off base in my design thoughts? Does anyone have any points to add in favor of one or the other?
Hell, why not just make one giant class called "Do" and one method on it called "It" and pass the whole universe into the It method?
Do.It(universe)
Keep things as small as possible. Discrete means easier to debug when things inevitably break.
My view is that you give the class the smallest set of "stuff" it needs for it to do its job. The "Application" method is easier upfront but as you've seen already, it will lead to maintainence issues.
I thing Steve McConnel put it very succintly. He states,
"The difference between the
'convenience' philosophy and the
'intellectual manageability'
philosophy boils down to a difference
in emphasis between writing programs
and reading them. Maximizing scope
may indeed make programs easy to
write, but a program in which any
routine can use any variable at any
time is harder to understand than a
program that uses well-factored
routines. In such a program you can't
understand only one routine; you have
to understand all the other routines
with which that routine shares global
data. Such programs are hard to read,
hard to debug, and hard to modify." [McConnell 2004]
I wouldn't go so far as to call the Application object a "god" class; it really seems like a utility class. Is there a reason it isn't a public static class (or, better yet, a set of classes) that the other classes can use at will?