How to avoid creating huge classes [closed] - oop

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..

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

Command Pattern leading to class explosion [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 6 years ago.
Improve this question
It seems like whenever I use the Command Pattern, it always leads to a significantly larger number of classes than when I don't use it. This seems pretty natural, given that we're executing chunks of relevant code together in separate classes. It wouldn't bother me as much if I didn't finish with 10 or 12 Command subclasses for what I might consider a small project that would have only used 6 or 7 classes otherwise. Having 19 or so classes for a usual 7 class project seems almost wrong.
Another thing that really bothers me is that testing all of those Command subclasses is a pain. I feel sluggish after I get to the last few commands, as if I'm moving slower and no longer agile.
Does this sound familiar to you? Am I doing it wrong? I just feel that I've lost my agility late in this project, and I really don't know how to continuously implement and test with the speed that I had a few days ago.
Design patterns are general templates for solving problems in a generic way. The tradeoff is exactly what you are seeing. This happens because you need to customize the generic approach. 12 command classes does not seem like a lot to me, though, personally.
With the command pattern, hopefully the commands are simple (just an execute method, right?) and hence easy to test. Also, they should be testable in isolation, i.e. you should be able to test the commands easily with little or no dependencies.
The benefit you should be seeing are two-fold:
1) You should have seen your specific, complicated approach simplified by using the pattern(s) you chose. i.e. something that was getting ugly quickly should now be more elegant.
2) Your should be going faster, due to the simplified approach and the ease of testing your individual components.
Can you make use other patterns, like composite, and use good OO design to avoid duplicating code (if you are duplicating code...)?
That doesn't seem like a lot of command classes, but I agree with you that it smells a little if they make up more than 60% of your classes. If the project is complex enough to merit the use of the command pattern, I suspect you'll find some classes begging to be split up. If not, perhaps the command pattern is overkill.
The other answers here have great suggestions for reducing the complexity of your commands, but I favor simplicity where I can find it (ala the bowling game).

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.

do you rely on your memory or consult references and use a lot of intellisense? [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
I have noticed I do not code as much as I use to. Today I dedicate more time to analysis and design, then I communicate that design to programmers. Then they do the coding. This has affected my coding productivity, because I must consult references and rely on intellisense. Things are becoming more complex everyday
Now, here is the irony. If I were to hire a programmer and ask him/her to sit in front of a computer, I may ask to do some coding and I would check abilities. I would evaluate them based on their use of memory vs. consulting references. Maybe I will prefer that programmer who did not consult too much, but who knows what they are doing.
What is your opinion and experience?
I would say that a developer who knows how to find the answers is better than one who has an overall good knowledge already. I find that intellisense is a good tool for finding answers, besides it is too much to remember all method names, arguments, overloads, etc.
I use memory to get me into the right general area (e.g. knowing which classes to use or at least which namespace they'll be in) and then often Intellisense/MSDN for the exact method name or arguments to use.
Having said that, Stack Overflow is improving my ability to code without any references (or even compilation) - I'm sure code will just work out of the box for me more often now than it used to. (I tend to post and then check the code works, add links to MSDN etc - assuming I'm reasonably confident in the approach.)
Someone knowing what resources are available, and how to find the answers, and how to effectively debug - these are qualities I look for now in prospective employees.
I used to consult my memory only, but two things have happened:
Class libraries have gotten larger, so has the number of languages available
The ratio of programming-related memory to personal-life-related memory has shifted away from code
Programming today is also eight times harder than it was when I started. I used to work on 8-bit machines, now I'm working on 64-bit ones. :)
I once was at a job interviewed with the CTO of a company. He asked a question based on a real life problem the company had a while back and solved. It was a multi step problem.
I was standing in front of a whiteboard working through my solution and struggling through a particular part, a part I would use google for before even attempting it, had I been tasked with solving this problem for real instead of for an interview. He asked me at that point, "would you do anything different if this wasn't an interview question." I responded, "Yes. I would exhaust all possibilities of using a third party component for this part of the task and look up the solution, because it is a well defined problem thats been solved several times." There was a bit more discussion where I justified my answer, explained exactly what I would research, and I solved some other parts of the question. In the end I was offered and accepted the job, partly because of knowing how to find out what I didn't know.
Being able to use references is as important as being able to code from memory. Obviously, if you are a one language shop, and want people proficient in that language,the person should be able to write a complete hello world app in notepad. Interview problems should focus on small problems, and one should not worry about small syntax errors. This is why a whiteboard is the best IDE for interview questions.
Unless you demand all your coders use notepad and don't give them internet access, don't be as concerned by the syntax. If you do sit them down in front of a computer, worry about the finished product as well as the technique used to get there.
I'm a PHP programmer in my early 30's. I rely on PHP's excellent documentation, for several reasons:
Programming concepts don't change. If I know what my object models are and how I want to manipulate data, then there's dozens of ways to implement the details. The details are important, but a better grasp of the design and structure is more important
PHP has notoriously inconsistent functions. One string function might use ($needle,$haystack) as parameters, and another might use ($haystack,$needle). Trying to keep them straight isn't worth the hassle when you can just type php.net/function_name and get the reference.
I don't rely on intellisense, simply because I haven't found a decent IDE for PHP that does it well. Eclipse is ok, but it's not fantastic. Netbeans gives me 'PHPDoc not found' for all the built-in PHP functions whenever I install it. There's nothing that I've found so far that beats out the documentation.
The bottom line is that the ability to memorize functions isn't indicative of coding ability. Obviously there's a key set of basic functions that a good programmer will know just from extensive usage over time, but I wouldn't base a hiring decision on whether someone knows substr_replace vs. str_replace from memory.
Because I've read either the documentation, or articles, or a book on a subject, the things I learn on a topic are organized. The result is that, if I can't bring something up from memory, I can probably find it quickly through IntelliSense or the Object Browser.
Worse come to worst, I can pick up the book again; something these youngsters are not being taught to do.
John Saunders
Age 51
Pretty much Google + Old Projects + my memory (of course)
References will not solve your problems though, its only for the nuts and bolts, the higher level of problem solving is the actual "programming" part IMHO.
I tend to use Intellisense and Resharper much more than I used to before, but this has helped my overall productivity. If I can get the idea of how I want to solve something and then use tools to get the more boring parts like class names and function signatures, why shouldn't I use the tools I have? I feel relieved that Jon Skeet has a similar approach it seems.
I rely on my bookmarks and books... and my ability to use them effectively. I have multiple books above my desk, including a copy of the ISO C90 standard. Moreover, I use Xmarks to have access to my bookmarks wherever I go. Sometimes, I make a pdf out of a particular page and upload it to my web-site if it is important enough.
Sometimes the information provided by the resources I use makes its way into my terrible memory... maybe.

Allocating resources for project documentation [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
What would you suggest for the following scenario:
A dozen of developers need to build and design a complex system. This design needs to be documented for future developers and the design decisions must be noted. These reports need to be made about every two months. My question is how this project should be documented.
I see two possibilities. Each developer writes about the things they helped design and integrate and then one person combines each of these documents together. The final document will probably be incoherent or redundant at times since the person tasked of assembling everything won't have much time to adjust every part.
Assume that the documentation parts from each developer arrive just a few days before deadline. A collaborative system (i.e. wiki) wouldn’t work properly since there wouldn’t be anything to read until a few days before deadline.
Or should a few people (2-3) be tasked with writing the documentation while the rest of the team works on actually developing the system? The developers would need a way to transfer their design choices and conclusions to the technical writers. How could this be done efficiently?
We approach this from 2 sides, using a RUP style approach. In the first case, you'll have a domain expert who is responsible for roughing out the design of what you're going to deliver - with developers chipping in as necessary. In the second case, we use a technical author - they document the application, so they should have a good idea of how it hangs together, and you involve them right through the design and development process. In this case, they can help to polish the design, and to make sure that it matches what they thought was being developed.
We use confluence (atlassian's wiki-like-thing) and document all kinds of different "things". The developers do it continiously, and we push each other for docs - we let peer pressure decide what is necessary. Whenever someone new comes along he/she is tasked with reading through everything and to find out what still is correct. The incorrect stuff is either deleted or updated as a consequence of this. We're happy when we can delete stuff ;)
The nice thing about this process is that the relevant stuff stays and the irrelevant stuff is deleted. We always "got away" from the more formalized demands by claiming that we could always construct the word documents they wanted if "they" needed them. "They" never needed them.
I think alternative 2 is the less agile, because it means a new stage to the project (although it may be in parallel with tests).
If you are in an agile model, then just add documentation (following a guideline) as a story.
If you are in a staged approach, then I would nevertheless ask developers to work on documentation, following some guidelines, and review that documentation along the design and the code. Eventually, you may have a technical writer reviewing everything for proper English, but that would be a kind of "release" activity.
I think you can use Sand Castle to document your project.
Check it out
Sand Castle from Microsoft
It's not a complete documentation, but making sure that interfaces etc. are commented using Doxygen-style comments means writing code and documenting it are closer together.
That way, developers should document what they do. I still think a review by the architect(s) is needed to ensure consistent quality, but ensuring people document what they do is the best way to ensure they follow the architecture.