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.
Related
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... :-)
I have a class that basically represents the parameters of a model, and encapsulates the logic to calculate values of the model with those parameters. I'm trying to decide if this class should be immutable. In practice, instances of the model will be generated by fitting to some data set, so in that sense it makes sense (to me at least) for that instance to be immutable since it's tied to external data.
On the other hand, there will be a GUI to let a user do a "what-if" wherein they can change the parameters to see how it changes model values. So I could make the model mutable to make this easy, or create new copies every time a parameter is changed. The latter seems awkward, especially if there are e.g. 5 parameters that could be ticked up and down individually...seems like I would have to implement a SetX() method for each parameter which returns a copy, right?
Am I overthinking this, or is there a proper pattern to use here? (This is C# code, though I guess not really language-specific)
Consider carefully how the object is going to actually be used for your speculative analysis. For straightforward, one-off, let's-mutate-the-field-try-something-and-change-it-back scenarios, sure, just make it mutable. But suppose you want to pull out the big guns; then it becomes much nicer to have an immutable model.
Data d = whatever;
// What if we mutate X and Y? Which one maximizes the value of Foo(d) ?
var query = from x in Range(0, 100)
from y in Range(0, 100)
let mutated = data.MutateX(x).MutateY(y)
orderby Foo(mutated)
select mutated;
var max = query.First();
And so on. With an immutable pattern it becomes much easier to write speculative queries, it becomes much easier to parallelize those queries across multiple cores, and so on.
The latter seems awkward
Well that's your answer. The goal of API design is to make writing code as easy as possible. If a particular pattern makes it more difficult or awkward than the alternative, the alternative is probably correct.
I think you're probably overthinking this a little bit. While there is probably a very elegant design pattern for this that uses eight classes and four interfaces, I think the simplest route forward would be to make it a normal, mutable class. Think about your intention: you want a Model that can be loaded from external data (perhaps a static method returning a Model instance) with parameters that can change according to user input. This seems like a use case for your everyday, garden variety Class.
You may also choose to separate your classes into a Data class and Strategy class, the second which contains the changeable parameters and uses something like a Strategy pattern to calculate the results.
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.
This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 9 years ago.
Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?
Here's what I normally do, but I'm wondering if there's a standard way?
Nested Classes or Enums
Fields
Properties
Events
Constructors
Public Methods
Private Methods
Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.
Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.
I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:
Cause An element within a C# code
file is out of order in relation to
the other elements in the code.
Rule Description A violation of this
rule occurs when the code elements
within a file do not follow a standard
ordering scheme.
To comply with this rule, elements at
the file root level or within a
namespace must be positioned in the
following order:
Extern Alias Directives
Using Directives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Within a class, struct, or interface,
elements must be positioned in the
following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complying with a standard ordering
scheme based on element type can
increase the readability and
maintainability of the file and
encourage code reuse.
When implementing an interface, it is
sometimes desirable to group all
members of the interface next to one
another. This will sometimes require
violating this rule, if the interface
contains elements of different types.
This problem can be solved through the
use of partial classes.
Add the partial attribute to the class, if the class is not already
partial.
Add a second partial class with the same name. It is possible to place
this in the same file, just below the
original class, or within a second
file.
Move the interface inheritance and all members of the interface
implementation to the second part of
the class.
I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.
To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.
I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
But the main thing is keeping it consistent and purposeful.
I tend to clump private data and tend to clump related methods/properties in functional groups.
public class Whatever {
// private data here
int _someVal = kSomeConstant;
// constructor(s)
public Whatever() { }
#region FabulousTrick // sometimes regionize it
// fabulous trick code
private int SupportMethodOne() { }
private double SupportMethodTwo() { }
public void PerformFabulousTrick(Dog spot) {
int herrings = SupportMethodOne();
double pieces = SupportMethodTwo();
// etc
}
#endregion FabulousTrick
// etc
}
You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.
As said, I don't think there is a best way as such. But some organisation does help you the programmer.
How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.
So I make use of the #region a lot to in this sort of way -
region Events : All of the event references that this class uses (at least in this particular partial class).
region Controls : All functions that directly interact with controls on a form.
region MDI : set the mdi up
Then there will be some to do with functionality rather than interface,
region Regex searches
I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.
You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.
Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.
Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.
Each to their own, but I tend to follow the same order that the MSDN help follows.
I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).
IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.
On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.
I use the following layout:
events
globals/class-wide fields
private/internal
properties
methods
public/protected
properties
methods
nested classes (although I try to avoid these whenever possible)
I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.