What design pattern(s) to use? [closed] - oop

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to design an easily extensible item system for my game where I don't need to modify existing code much. I want to add items with new effects on the fly.
Traits my items have in common:
A name,
a description,
an npc sell price,
if it can be equipped,
required level,
if it is usable in battle,
if it is usable outside of battle,
a cooldown
So I can encapsulate this already into a class. But now there are item effects.
Example:
heals x health points,
heals x mana points,
removes debuff x,
adds buff x,
gives x stat points on equipping,
has x% chance to create some other effect when equipped,
etc.
And those can be combined like: heals x health and mana points. The first four are examples for effects a usable item can have while the last two are examples for effects equipable items can have.
The idea behind it is that I have this structure in a database as well and I can add a new item with a new effect combination in my database, my code reads this then and builds it together into a new fancy item, without me having to modify much. The only time I need to modify my code is when I add new effects obviously.
How would you put this together in design pattern(s)?
I thought of decorator. Is there a different, better design pattern for this or maybe even a combination of multiple design patterns?

It seems a decorator pattern is good for your needs. Think of a pizza with different tops. You can warp the basic pizza with many tops and at the end you call a function to sum the prize or whatever. It's a kind of wrapper and you pass the object to the next class. Hence you need only a basic class and can add new (top)-class when you need it.

You can use Decorator Pattern to decorate your objects with additional functionality without modifying them.

This isn't a direct answer to your question, though I believe it needs more words than can fit into a comment:
Picking a design pattern for a chunk of code is not something which you would typically do up-front (If you do it this way, be prepared to change it after you've seen it working); it's something which you're more likely to do after you already have some working code in-place and are looking to refactor it. - Chances are that whatever decisions you make now will be affected by many (currently) unknown factors once you've started writing code.
I'd suggest thinking more about the features, behaviour and functionality which you'd like to create, and then just begin writing code to see what works and further develop your ideas. Trying to solve a problem by designing it up-front around buzzwords like "factory", "decorator", "visitor" etc most likely won't lead you to a solution - design is very much an iterative process of continual improvement, change and refinement.
As an aside, and specifically on OO design, have a careful think about the SOLID principles while you're writing code; they should help you make decisions when you come to refactoring
http://www.blackwasp.co.uk/SOLIDPrinciples.aspx
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Related

OOP(Object Oriented Programming) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
This is not a specific question about a certain piece of code and apologies if my current question is not valid on StackOverflow. With Such a big Community I am just curious to find a common approach for best practices.
It's not that I Don't know how to code the OOP way, but while my code keeps growing I am losing track and my code actually bluntly stated gets "ugly". What happens is that it takes a lot of time to rewrite my code to finally have it correct again.
Don't get me wrong. I really take time and dedication to adapt my code the best way I can. I rewrite parts that can be rewritten etc. Actually I want to avoid to rewrite and I know it takes alot of practice. Any Guidelines/Tips regarding taking on a project is highly appreciated.
I Have written Code already in OOP way, but it's small code/project based and now when I am starting to take on bigger projects I lose track.
My question is simply: Am I the only one that has this? And how to keep my coding neat all the way to the end?
Thanks in advance for any tips regarding this situation. I just want to write better and cleaner code.
In practice, you often might need to update your existing code to meet the new requirements. But if this is something you are doing on regular basis, then it is possible that your development process is not good enough.
You may lack a beforehand thinking and planning process.
What do you do when you have a new development task? Do you just go on and write some code?
I use the process like this:
1) User story.
Describe a user story, it often comes from the customer or users. This can be something like "I want to have a new beautiful chart of the recent data on the dashboard".
2) Requirements specification. Start asking questions and add details. You may need to create a separate document just to describe all the details - what data exactly should be shown, should it be line or bar or other kind of chart, where exactly should the chart be placed, etc, etc...
Result - a detailed requirements specification. It should be clear enough so you can give it to other developer, who should be able to continue with following steps without asking the questions.
Check also this article 10 Typical Mistakes in Specs.
3) Implementation details. Think how to implement the requirements, describe the classes structure and objects interaction, think on extensibility and flexibility, plan the unit tests for your code.
The basic idea is that you start writing and re-writing your code even before you actually write the real code.
Imagine how your classes / objects will be used, try to write some tests before actually writing the code.
Here is where SOLID principles, design patterns and UML diagrams can be useful to design your code in a good way.
4) Estimation. If you was good at point (3), it will be trivial to split your implantation into small steps and estimate how much time you will need for every step, like:
Database migration - add new tables - 1h
Implement ClassA, ClassB, ClassC - 1h
Implement ClassD, with a special calculation algorithm - 4h
Unit tests - 2h
Testing, fixing bugs found - 20% of the above
I usually use this scheme of estimation (along with 20% for unexpected things) and it is possible to get very accurate estimations. Like for a 40 hour task it can be 1-2 hours error, it should never be something like 50% error.
5) Implementation. Here you just go on and do the task.
Everything is planned, everything is absolutely clear.
No thinking on design and strategy, only local decisions (like do I use for or while loop here?).
This way you minimize the amount of "surprises" during the implementation and reduce the need in re-writing the code later.
Always keep SOLID in mind. That will help you to stay on the right track. Here is a good start http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

It's possible to design a program that works like cells in a human body (or life)? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I always think that life in general is really very complex and we don't even know all about it. But it works, right? that lead me to think if it was possible to think of a program as thinking of a group of differentiated cells. or maybe totipotent (the ones that can differentiate in any other cell) cells that differentiated.
I don't know if this is the right place to ask because involves biology and reprogramming.
thanks for interest
If your question is as stated in the title the you ought to look into Artificial Life and Digital Life. The prime example of Digital Life is Avida, where you have a bunch of computer programs thought of as organisms who compete for computer resources (such as CPU time and memory). Another example is the research by Schlessinger et. al. (paper here). They created digital single-celled organisms that could aggregate into a multi-cellular organism. Furthermore, the cells in their research are differentiated in that not all of them can perform all actions.
Moreover, there is a fair amount of research on computer simulations of morphogenesis, embryogenesis, cell differentiation, cell division etc.
The established field of Genetic Algorithms might be worth exploring:
http://www.catonmat.net/blog/genetic-algorithms-101/
http://delicious.com/tag/geneticalgorithm
Your question is very vague. But you should consider to look in the field of Systems Biology. If you are interested I provide you an article by H. Kitano Systems biology: A brief overview
During my internship I have been simulating/modeling a very simple cell of a microorganisms to study its behavior. But from my understanding to simulate a cell of human body is extremely difficult to do not to speak of modeling an eukarotic cell...
Programs basically already work this way.
The linux fork() command - duplicate the current process, and starts running it from the the same point in both processes. The program "knows" if this program is the original or the forked one, and invokes a code with respect to it [if the programmer designed it to do it, of course]
Also note, that like cells - all linux processes have the same origin - there is one process which is responsible for creating all others.

Any good tutorials or resources for learning how to design a scalable and "component" based game 'framework'? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In short I'm creating a 2D mmorpg and unlike my last "mmo" I started developing I want to make sure that this one will scale well and work well when I want to add new in-game features or modify existing ones.
With my last attempt with an avatar chat within the first few thousand lines of code and just getting basic features added into the game I seen my code quality lowering and my ability to add new features or modify old ones was getting lower too as I added more features in. It turned into one big mess that some how ran, lol.
This time I really need to buckle down and find a design that will allow me to create a game framework that will be easy to add and remove features (aka things like playing mini-games within my world or a mail system or buddy list or a new public area with interactive items).
I'm thinking that maybe a component based approach MIGHT be what I'm looking for but I'm really not sure. I have read documents on mmorpg design and 2d game engine architecture but nothing really explained a way of designing a game framework that will basically let me "plug-in" new features into the main game.
Hope someone understands what I mean, any help is appreciated.
If you search for component-based systems within games, you will find something quite different to what you are actually asking for. And how best to do this is far from agreed upon just yet, anyway. So I wouldn't recommend doing that. What you're really talking about is not really anything specific to games, never mind MMOs. It's just the ability to write maintainable code which allows for extension and improvements, which was a problem for business software long before games-as-a-service became so popular and important.
I'd say that addressing this problem comes primarily from two things. Firstly, you need a good specification and a resulting design that makes an attempt to understand future requirements, so that the systems you write now are more easily extended when you come to that. No plug-in architecture can work well without a good idea of what exactly you hope to be plugging in. I'm not saying you need to draw up a 100-page design doc, but at the very least you should be brainstorming your ideas and plans and looking for common ground there, so that when you're coding feature A, you are writing it with Future feature B in mind.
Secondly, you need good software engineering principles which mean that your code is easy to work with and use. eg. Read up on the SOLID principles, and take some time to understand why these 5 ideas are useful. Code that follows those rules is a lot easier to twist to whatever future needs you have.
There is a third way to improve your code, but which isn't going to help you just yet: experience. Your code gets better the more you write and the more you learn about coding. It's possible (well, likely) that with an MMO you are biting off a lot more than you can chew. Even teams of qualified professionals end up with unmaintainable messes of code when attempting projects of that magnitude, so it's no surprise that you would, too. But they have messes of code that they managed to see to completion, and often that's what it's about, not about stopping and redesigning whenever the going gets tough.
Yes, I got what you want...
Basically, you will have to use classic OOP design, the same one that business software coders use...
You will first have to lay out the basic engine, that engine should have a "module loader" or a common OOP-style interface, then you either code modules to be loaded (like, as .dlls) or you code directly within your source code, using that mentioned OOP-style interface, and NEVER, EVER allow a module to depend on each other...
The communication, even inside your code, should be ALWAYS using a interface, never put "public" vars in your modules and use it somewhere else, otherwise you will end with a awfull and messy code.
But if you do it properly, you can do some really cool stuff (I for example, changed the entire game library (API that access video, mouse, keyboard, audio...) of my game, in the middle of development... I just needed to recode one file, that was the one that made the interface between logic, and game library...)
What you're thinking about is exactly what this article describes. It's a lovely way to build games as I have blogged about, and the article is an excellent resource to get your started.

How to avoid creating huge classes [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Stackoverflow users,
How do you keep yourself from creating large classes with large bodied methods. When deadlines are tight, you end up trying to hack things together and it ends up being a mess that needs refactoring.
One way is to start with test driven development and that lends itself to good class design as well as SRP (Single Responsibility Principle).
I also see developers double clicking on controls and typing out line after line in the event method that gets fired.
Any suggestions?
I guess it depends on your internal processes as much as anything.
In my company, we practise peer review, and all code that gets comitted must be 'buddied in' by another developer, who you have to explain your code to.
Time constraints are one thing, but if I review code that has heinously long classes, then I won't agree to the check-in.
It's hard to get used to at first, but at the end of the day, it's better for everyone.
Also, having a senior developer who is a champion for good class design, and is willing and able to give examples, helps tremendously.
Finally, we often do a coding 'show and tell' session where we get to show off our work to our peers, it behooves us not to do this with ugly code!
Use a tool like Resharper and the Extract Method command.
Long classes is one bad code smell of many possible.
Remedying overly large classes by creating lots of small ones may create its own problems. New engineers on your project may find it difficult to follow the flow of the code to work out what happens where. One artifact of this problem can be very tall call stacks, execution nesting through many small classes.
Another suggestion is to do only what is asked. Don't play the "What if" game and try to overdesign a solution. This has the "Keep it simple, stupid" idea behind it.
We're a java and maven shop, and one of the...I guess you could say forensic methods we use are the excellent FindBugs, PMD and javancss plugins. All will give warnings about excessive length in a method, and the cyclomatic complexity calculations can be very eye opening.
The single most important step for me to avoid large classes that often violate SRP was to use a simple dependency injection framework. This freed me from thinking too much about how to wire things together. I only use constructor injection to keep the design free from cycles. Tools like Resharper help to initialize fields from constructor arguments. This combination leads to a near zero overhead for creating and wiring up new classes, and implicitly encourages me to structure behavior in much more detail.
This all works best if data is kept separate from behavior, and your language supports constructs like events that can be used to decouple communication that flows in the downward direction of the dependency graph.
use some static code analysis tools in your automated builds and write/configure/use some rules so that for example someone has to write a justification when he/she breaks it..

Are KISS and YAGNI at odds with the trends towards increasingly more sophisticated patterns and practices like SOA, DDD, IoC, MVC, POCO, MVVM? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 13 years ago.
It seems to me that Agile methodologies encourage us to keep things simple, and lean, and not add complexity and sophistication until its needed. But the pace and volume of technology change encourages the use of increasingly abstract, complex and sophisticated tools and patterns to solve problems that we may not have yet (and may never encounter) in complex ways with significant learning curves and significant investments of effort.
Are KISS and YAGNI at odds with the trends towards increasingly more sophisticated ...
A car has an accelator and a brake, and a steering wheel that can turn left and/or right: it's up to the drivers to decide which to use when.
I'll keep my answer short and let the experts lay it out better...
I think that KISS applies to everything you listed. You mention increasing abstraction and complexity, which, I think, balance eachother.
The systems we are developing today must be complex, because, most of the time, the solution to a complex problem is inherently complex. However, to keep things simple, we use abstraction. Even if our complex system is built with, say, eight layers, we can follow KISS by keeping each layer simple.
For instance, to pick an item or two off your list:
SOA is not complex because we can wrap service calls in a wrapper object. This object handles the connection and makes calls, which are pretty easy to do because they simply pass parameters on.
MVC is not complex because we clearly separate our logic. We have a simple controller for directing requests and setting up data, a simple model to represent our domain, and a simple view that displays whatever data is passed to it.
However, in both of these cases, the pattern as a whole (or the system, if you will) is complex and non-trivial. It is the fact that we consider small, simple parts one at a time, and then fit them together, that lets us maintain our mental model as we work.
I agree with ChrisW's answer.
The idea is to stick with KISS and YAGNI as much as possible, but when the need arises and you need a sophisticated / complex solution, stand on the shoulders of giants and use proven patterns to guide you. These patterns and practices are meant to simplify your work, if using them is harder than the hack alternative, you should stick with the hack. Just make sure you take into account maintainability etc.
As an example, when you build the 1st version of a website it may consist of 1 or 2 main functionalities and just a few pages. You probably don't need MVC for this (even though it might be nice to start that way)
BUT, after you add a few more features and you have dozens of pages to manage along with how to share functionality between them, it might become apparent that you need MVC to better structure your application.
Similarly, if from the get go you know you will have to deal with something like returning multiple views of a common piece of data, MVC simplifies your problem by laying out a pattern for you to follow.
In summary, YAGNI now, but if you need it later then KISS by using a known pattern / solution.
Sigh.
We must have increasingly sophisticated and abstract components to match the demand for increasingly sophisticated software.
Most of us have limited brain space. We must learn to cope with our limited brains by using more sophisticated abstractions.
The alternative is not using abstractions, limiting ourselves to machine code.
Please read http://www.cs.utexas.edu/~EWD/transcriptions/EWD01xx/EWD117.html
"In spite of all its deficiencies,
mathematical reasoning presents an
outstanding model of how to grasp
extremely complicated structures with
a brain of limited capacity. And it
seems worthwhile to investigate to
what extent these proven methods can
be transplanted to the art of computer
usage. In the design of programming
languages one can let oneself be
guided primarily by considering "what
the machine can do". Considering,
however, that the programming language
is the bridge between the user and the
machine --that it can, in fact, be
regarded as his tool-- it seems just
as important to take into
consideration "what Man can think". It
is in this vein that we shall continue
our investigations."
I'm going to make a subjective answer (so sue me). I think that if you program by acronyms then you are going to run into trouble.
At the end of the day you are trying to make money for a business, or hopefully yourself. As such each decision you make is an engineering decision based on cost, time and benefits. You have to evaluate the use of a technique on the cost of implementation, maintenance etc, and make the best choice.
I think the only fair answer is that the tools and techniques chosen have to match with the desired goal of the engineering.
Its a matter of the right tool for the right job. The problem is when architects and/or developers begin to believe that a particular methodology or technology is a "golden hammer." That is when things become religious, and religion and reason do not play nicely together ;)
Oh and by the way, "agile" does not necessarily mean you don't use some of the acronyms you mention, or some framework that implements them. Those decisions are usually made far in advance of implementing the sorts of things that developers have come to associate with agile, e.g. user stories, sprints, etc.
First off, the list of acronyms doesn't really necessarily make sense - there's not really much simpler than POCO, for example...
However, KISS and YAGNI are achieved most effectively, in many circumstances, by using concepts like IoC, MVC, and MVVM - provided you use the patterns correctly.
Patterns aren't complicated, in and of themselves. It may take a bit of learning to understand what the pattern is trying to accomplish, but often, a pattern exists purely to simplify either code, maintenance, or usability - and usually all of the above. This fits in perfectly with keep it simple, for example.
IMHO, you (generally) don't want to start out with a complicated design. Could this be a local method rather than a service? Do I need an IoC container yet? This is particularly relevant when it comes to design patterns.
However, as you test and refactor your code, certain patterns (such as Ioc) will help you to achieve goals such as testability and DRY (Don't Repeat Yourself). If you know design patterns well, you can apply them at the appropriate time.
yes
-- this space intentionally left blank --