When do you define a class? - c#

Say you want to write a Tetris clone, and you just started planning.
How do you decide what should be a class? Do you make individual blocks a class or just the different block-types?
I'm asking this because I often find myself writing either too many classes, or writing too few classes.

Take a step back.
I suspect that you're putting the cart before the horse here. OOP isn't a Good Thing in its own right, it's a technique for effectively solving problems. Problems like: "I have a large multiple-team organization of programmers with diverse skill sets and expertise. We are building large-scale complex software where many subsystems interact with each other. We have a limited budget."
OOP is good for this problem space because it emphasizes abstraction, encapsulation, polymorphism and inheritance. Each of those works well in the many-teams-writing-large-software space. Abstraction allows one team to use the work of another without having to understand the implementation details, thereby lowering the communication cost. Encapsulation allows one team to know that they can make changes to their internal structures to make them better without worrying about the costs of impacting another team. Polymorphism lowers the cost of using many different implementations of a given abstraction, depending on the current need. Inheritance allows one team to build upon the work of another, cleanly re-using existing code rather than spending time and money re-inventing it.
All of these things are good not in of themselves, but because they lower costs in large-team-complex-software scenarios.
Do they lower costs in one-guy-trivial-software scenarios? I don't think they do; I think they raise costs. The point of inheritance is to save time through code re-use; if you spend more time messing around with getting the perfect inheritance hierarchy than the time you save through code re-use, it's not a net win, it's a net loss. Similarly with all the others: if you don't have many different implementations of the same thing then spending time on polymorphism is a loss. If you don't have anyone who is going to consume your abstraction, or anyone from whom you need to protect your internal state, then abstraction and encapsulation are costs with no associated benefits.
If what you want to do is write Tetris in an OO style for practice writing in that style, by all means go right ahead and don't let me stop you. I'm just saying: don't feel that you have a moral requirement to use OOP to solve a problem that OOP is not well-suited to solve; OOP is not the be-all-and-end-all of software development styles.

You might want to check out How do you design object oriented projects?. The accepted solution is a good start. I would also pick up a design patterns book as well.

For a Tetris clone you're going to be better off I'd say creating a block class and using an enum or similar to record what shape piece it is. The reason is that all blocks act in the same way - they fall, they react to user input by rotating or falling faster, and they use collision detection to determine when to stop falling and trigger the next piece.
If you have a class per block-type then there'd be so little difference between each class that it would be a waste of time.
In another situation where you have a lot of similar concepts (like many different types of animals etc.) it might make mroe sense to have a class per sub-type, all inheriting from a parent class if the sub-types were more different from each other

Depends on your development methodology.
Assuming you do agile, then you can start with writing the classes you think you'll need. And then as you start filling in the implementation, you'll discover that some classes are obsolete or others need to be split out.
Assuming a more design-first-then-build approach (dsdm/rup/waterfall...), then you'd want to go for a design based on the "user story", see SwDevMan81's link for an example.

I would make a base-class Piece, because they each have similar functionality like move right, move left, move down, rotate CW, rotate CCW, color, position, and the list goes on. Then each piece should be a sub class like ZPiece, LPiece, SquarePiece, IPiece, BackwardsLPiece, etc... You probably do have many classes, but there are many different types of pieces.
The point of OOP you are asking about is inheritence. You don't want to reinvent the wheel when it comes to some functions like move left/right/down, nor do you want to repeat exact code in multiple locations. Those functions shouldn't change depending on the piece so put it in the base class. Each piece rotates differently, but it is in the base class because each class should implement it's own version of it.
Basically, anything all pieces have in common should be in a base class. Then everything that makes a piece unique should be in the class itself. Yes, I think making a block class and each piece has 4 of them is a bit much, but there are those that would disagree with me.

Related

The concept of classes is ok if i have a single user application and i work alone at it and just i'll use it?

I make an app in c# with windows forms and all my code is behind the window code, so i have for now 2500+ lines of code and some of my collegues say to use classes to divide the code by functionalities but i don't find a purpose in that because everything will be made public and so on.
None of them know to explain me why it is the best approach, but just give me vague hints like : "if you do a modification somewhere your other functions will crash" and i don't know how that is possible...
I searched and find a keyword "partial" so what should i do? Should start learning classes and so on?
You need to go right back to the basics, and not be put in charge of writing an application by yourself. Ask your employer to excuse you from your responsibilities whilst you learn how to do them, you're just digging yourself a deeper hole with every line of code you write at the moment.
A class is designed to be a reusable block of code. the class is for relating functionality together. the class is for classing things into a particular set of instructions.
This is the idea and reasoning behind OOP.
Consider a Road, a Road can have 0 to x cars on it. All of the cars can "drive" and they can "turn" they can even leave the road and join another road. They work together but are not one and the same thing. A car can drive but a road cannot. You dont want to have a "Road" class with 900000 methods for different cars all with their own drive methods and "leave road" method... You have 1 "class" which you can create multiple times into different occurances of that class, which may or may not be on that road.
Not to labour the analogy but it's a very popular one. Your code is not all doing the same thing even if you think it is, You have to scope your opinion correctly. You may have file access code next to UI code next to Business logic code next to network communication code. they are all pieces in the puzzle of "My Application", but within "My Application" they are not doing the same thing. It is with this kind of thought that you need to move forward and not with "It's just me, Writing this same application, it all goes here"
The main answer for which you should divide your code into classes is code reusability. You could greatly benefit from techniques of object oriented programming such as inheritence, polymorphism and so on.
Moreover, the time invested in learning Object oriented programming is a time invested in you, and for your greater understanding of different programming languages or frameworks which you may be using in the future.
Although you could do this project all by yourself and without using any classes, I strongly recommend you to try and learn OOP programming.
PS: C# is an object oriented programming language, which means that all object and variable type you may be using are classes!

Template pattern - not useful for small projects

I'm sorry to ask such a localized question but until I get confirmation I don't feel confident moving on with my project.
I have read lots about the template pattern, Wikipedia has a good example.
It shows that you create the basic virtual methods and then inherit the base class and override where you want. The example on the site is for Monopoly and Chess which both inherit the base class.
So, my question is, if you had an application which was only going to be Chess and never anything else, would there be any benefit in using the template pattern (other than as an education exercise)?
No, I think that falls under the category of "You Ain't Gonna Need It."
To be more specific, design patterns exist to solve a particular problem, and if your code doesn't need to solve that problem, all they do is add lines of code without having any benefit.
No. Expressed in a very simplified and superficial way, the template pattern is just worthwhile starting at a certain relationship between total code size and templated code size. In your example, the chess game is going to be the entire program, so there'll be no need to use the template pattern here.
The template pattern is used in specific situations. It is used when you want to sketch out an algorithm but let the specific steps differ.
This could be useful in a Chess application. However, you should not start developing an application with the idea 'I'm going to use this pattern and that one and..'. Instead, you develop the code and you discover that you need certain patterns.
This is where a Test Driven Development approach is really handy. It allows you to refactor your code each step of the way.
A nice book that explains this is Refactoring To Patterns.
I would suggest writing your chess game and then if in the future coming back and changing things to fit monopoly too. But its something totally different if you want to use the pattern to learn the pattern, in that case its good to start simple so the complex is easier to understand.
It really depends on the parts of the program. The whole idea of Template is to have an algorithm that never changes and to be able to add or edit certain steps of that algorithm.
It may well be that you never change, however, this is the issue with design principles, it IS good practice and you may later wish you'd implemented them. I would say though that if you are 100% sure then you can leave it out as it usually saves time and lines of code. Depends if you want to learn Template usage or not.
Also the GOF principles website is quite good:

Should entities have the capability to draw themselves? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
A bit of a simple question but it's one I'm never too sure of. This is mostly in context of game development. Let's say you had an entity, like a ship or a character. Should (and I know this is a matter of opinion) this object contain a Draw method? (perhaps implement an IDrawable interface)
When looking at source code in some game projects I see this done in very many ways. Sometimes there is a separate class that may take in an Entity base object and draw it, given its properties (texture, location, et cetera). Other times the entity is given its own draw method and they are able to render themselves.
I hope this question is not too subjective.. Sometimes I hear people say things like drawing should be completely separate from objects and they should not know how to draw themselves or have the capability to. Some are more pragmatic and feel this kind of design where objects have this capability are fine.
I'm not too sure myself. I didn't find any similar questions to this because it may be a bit subjective or either method is fine but I'd like to hear what SO has to say about it because these kinds of design decisions plague my development daily. These small decisions like whether object A should have the capability to perform function B or whether or not that would violate certain design principles.
I'm sure some will say to just go with my gut and refactor later if necessary but that's what I have been doing and now I'd like to hear the actual theory behind deciding when certain objects should maintain certain capabilities.
I suppose what I am looking for are some heuristics for determining how much authority a given object should have.
You should go with whatever makes your implementation the easiest. Even if it turns out you made the wrong choice, you first hand experience on why one method is better than the other and can apply that knowledge in the future. This is valuable knowledge that will help you make decisions later. I find that one of the best ways I learn the merits of something is to do it a wrong a few times (not on purpose mind you) so you can get a good understanding of the pitfalls of an approach.
The way I handle it is this: An entity has all the information on it that is required for it to be drawn. e.g. The sprites that make it up, where they are located relative to the center of the entity. The entity itself does very little, if anything at all. It's actually just a place to store information that other systems operate on.
The world rendering code handles drawing the world as well as all the entities in it. It looks at a given entity and draws each of its sprites in the right spot, applying any necessary camera transformations or effects or what-have-you.
This is how most of my game works. The entity has no idea about physics either, or anything. All it is is a collection of data, which other systems operate on. It doesn't know about physics, but it does have some Box2D structures that hang off of it which Box2D operates on during the physics updating phase. Same with AI or Input and everything else.
Each method has it's pros and cons.
Advantage of letting objects draw themselves:
It is more comfortable for both parties. the person writing the engine just has to call a function, and the person using it, writing these IDrawable classes has low level access to everything they need. If you wanted to make a system where each object has to define what it looks like which shaders and textures it will use, and how to apply any special effects. You will either have a pretty complicated system, or a very limited one.
Advantage of having a renderer manage and draw objects
All modern 3D game engines do it this way, and for a very good reason. If the renderer has full control over which textures are bound, which models to use, and which shaders are active, it can optimize. Say you had a lot of items rendering with the same shader. The renderer can set the shader once and render them all in one batch! You can't do this if each object draws itself.
Conclusion
For small projects, its fine to have each object draw itself. It's more comfortable in fact.
If you really want performance and want to squeeze everything out of your graphics card, you need a renderer that has strict control over what is rendered and how, so that it can optimize.
It depends what you mean by 'draw itself'. If you mean should it contain low-level routines involving pixels or triangles, then probably not.
My suggestion:
One class to represent the behavior of the object (movement, AI, whatever)
One class to represent the appearance of the object
One class to define an object as combination of an appearance and a behavior
If the 'appearance' involves some custom drawing routine, that could be in that class. On the whole though drawing would be abstracted from underlying API perhaps and either using the strategy, visitor or some IoC pattern the object would be drawn by some rendering manager. This is especially true in game design where things like swapping textures in/out of video memory and drawing things in the correct order is important; something needs to be able to optimize things above the object level.
To try to be more specific, one part of your object's graph (object itself or appearance subdivision) implements IRenderable, has a method Draw(IRenderEngine), and that IRenderEngine gives the IRenderable access to methods like DrawSprite, CreateParticleEffect or whatever. Optimising or measuring your engine and algorithms will be far easier this way, and if you need to swap out engines or re-write in an unmanaged, high-performance way (or port to another platform), just create a new implementation of IRenderEngine.
Hint: if you do this, you can have many things that look the same/similar but act differently by swapping out the behavior, or lots of things that look different but act the same. You can also have the behavior stuff happen on a server, and the appearance stuff happen on a client.
I've done something very similar to this before. Each class of object had a base class that contained properties used on the client, but on the server it was a derived instance of that class that was instantiated, and it included the behavior (movement, simulation, etc). The class also had a factory method for providing its associated IRenderable (appearance) interface. Actually had a pretty effective multiplayer game engine in the end with that approach.
I suppose what I am looking for are some heuristics for determining how
much authority a given object should have.
I'd replace authority with responsibility and then the answer is ONE. Responsibility both for the behaviour and drawing of a ship seems too much to me.

How to decide on creating classes in an application..?

I am having some serious problem here. When do we need a class exactly?
Specifically, I thought of designing an desktop application that will be able to generate a profiling test or a unit test for any number of methods i specify. I was having a simple list for storing the methods. I did not think of having a class. But now, I thought of creating a class to store all the classes and gets the set of methods in the class. If this idea is correct, my last 4 days of effort is nullified. So putting up a new question if i can get some information.
Also I could not find the head or tail in my approach. So wanted to discuss with anyone who are interested in helping me with the design.
In general the rule to define the boundaries of a set of data and functionality to be moved into a class of their own is the single responsibility principle.
In Martin Fowler's excellent refactoring bliki you will find lots of patterns to move responsibilities, data and functionalities between classes (the obvious Extract Class, of course, but with the powerful aid of Extract Method and, in your case, Encapsulate Collection, maybe).
TDD is a good way to outline the design very early. Usually "easy to test" leads to "decoupled" and thus to separation of concerns.
Using both these approches together (TDD+Refactoring) may help you with the transition from a design to another: things should go a tad more smoothly.
And another excellent guideline is DIYDI (do it yourself dependency injection).
Also: are you going for code generation or runtime analysis here?
In the first case you might be interested in template engines which might save you a lot of work in the post-processing phase.
In the second case you might use Aspect Oriented Programming and/or Reflection to inspect the classes and find out what methods they have.
Please read this text by Grady Booch et al to get started into Objected Oriented Design.
Design can be quite difficult, and until you get some experience you are going to make bad choices, so write tests to make it easier to refactor your code. I would recommend reading, Code Complete. However since you probably want to get started right away and you question is directly asking about OO and classes I also recommend reading Uncle Bob's Blog post
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
Hope this helps
In a simple statement - If you have any data on which operations has to be performed, then you need a class. Good example for these are data containers like linklist, vector, ....
This is known as Object Based programming and is the first step of class designs.
The next step is Object Oriented (Inheritance, Polymorphism), the Proficiency for this comes with experience and looking at well designed codes.
If your application is not reusable (which is implied by the "desktop application") it is pretty much up to you to decide the granularity of your objects.
As long as you are fine with having (or not having) an additional classes there is no reason to change that.
If you are looking for principles for OO (object oriented design) there is plenty of literature and weblinks available.

SRP and a lot of classes

I'm refactoring some code I wrote a few months ago and now I find myself creating a lot of smallish classes (few properties, 2-4 methods, 1-2 events).
Is this how it's supposed to be? Or is this also a bit of a code smell?
I mean if a class does need a lot of methods to carry out it's responsibility, I guess that's how it's gotta be, but I'm not so sure that a lot small classes is particularly good practice either?
Lots of small classes sounds just fine :)
Particularly if you let each class implement an interface and have the different collaborators communicate through those interfaces instead of directly with each other, you should be able to achieve a so-called Supple Design (a term from Domain-Driven Design) with lots of loose coupling.
If you can boil it down so that important operations have the same type of output as input, you will achieve what Evans call Closure of Operations, which I've found to be a particularly strong design technique.
What tend to happen when you apply the SRP is that although all classes start out small, you constantly refactor, and from time to time it happens that a rush of insight clarifies that a few particular classes could be a lot richer than previously assumed.
Do it, but keep refactoring forever :)
Lots of small classes with focused responsibilties are what srp is all about. So, yes, this is the way things are "supposed to be" as far as srp advocates are concerned. But you're seeing an explosion of the number of classes in your system and it's beginning to become very difficult to remember or to intuitively know where things are actually done, isn't it? You are, indeed, exposing a new code smell, which is the (usually unnecessary) increase of complexity that comes aong with srp. I wrote an entry about it here. See if you might agree.
I think you have to find the middle way. Too many classes are sometimes overkill. From my side I try to separate concerns on a smaller level and if things are getting then refactor out more coarse grained:
First write separate concerns by extracting methods. If you can see a group of methods on data (instance + static fields) to form a dedicated responsibility 'extract class'. After a while if you can see different groupings of classes inside a package do 'extract packages'.
I found this (explosion) approach more natural as creating lots of classes and packages from start on. But this also depends...: If I can already see bigger components at the beginning I already create dedicated package structures.
Maybe some more details about your code to offer some more concrete help :)

Categories

Resources