Clean Code

Robert C. Martin

Mentioned 256

An extremely pragmatic method for writing better code from the start, and ultimately producing more robust applications.

More on Amazon.com

Mentioned in questions and answers.

If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

To search: Use the search box in the upper-right corner. To search the answers of the current question, use inquestion:this. For example:

inquestion:this "Code Complete"

Applying UML and Patterns by Craig Larman.

The title of the book is slightly misleading; it does deal with UML and patterns, but it covers so much more. The subtitle of the book tells you a bit more: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

Masters of doom. As far as motivation and love for your profession go: it won't get any better than what's been described in this book, truthfully inspiring story!

Beginning C# 3.0: An Introduction to Object Oriented Programming

This is the book for those who want to understand the whys and hows of OOP using C# 3.0. You don't want to miss it.

alt text

Mastery: The Keys to Success and Long-Term Fulfillment, by George Leonard

It's about about what mindsets are required to reach mastery in any skill, and why. It's just awesome, and an easy read too.

Pro Spring is a superb introduction to the world of Inversion of Control and Dependency Injection. If you're not aware of these practices and their implications - the balance of topics and technical detail in Pro Spring is excellent. It builds a great case and consequent personal foundation.

Another book I'd suggest would be Robert Martin's Agile Software Development (ASD). Code smells, agile techniques, test driven dev, principles ... a well-written balance of many different programming facets.

More traditional classics would include the infamous GoF Design Patterns, Bertrand Meyer's Object Oriented Software Construction, Booch's Object Oriented Analysis and Design, Scott Meyer's "Effective C++'" series and a lesser known book I enjoyed by Gunderloy, Coder to Developer.

And while books are nice ... don't forget radio!

... let me add one more thing. If you haven't already discovered safari - take a look. It is more addictive than stack overflow :-) I've found that with my google type habits - I need the more expensive subscription so I can look at any book at any time - but I'd recommend the trial to anyone even remotely interested.

(ah yes, a little obj-C today, cocoa tomorrow, patterns? soa? what was that example in that cookbook? What did Steve say in the second edition? Should I buy this book? ... a subscription like this is great if you'd like some continuity and context to what you're googling ...)

Database System Concepts is one of the best books you can read on understanding good database design principles.

alt text

Algorithms in C++ was invaluable to me in learning Big O notation and the ins and outs of the various sort algorithms. This was published before Sedgewick decided he could make more money by dividing it into 5 different books.

C++ FAQs is an amazing book that really shows you what you should and shouldn't be doing in C++. The backward compatibility of C++ leaves a lot of landmines about and this book helps one carefully avoid them while at the same time being a good introduction into OO design and intent.

Here are two I haven't seen mentioned:
I wish I had read "Ruminations on C++" by Koenig and Moo much sooner. That was the book that made OO concepts really click for me.
And I recommend Michael Abrash's "Zen of Code Optimization" for anyone else planning on starting a programming career in the mid 90s.

Perfect Software: And Other Illusions about Testing

TITLE Cover

Perfect Software: And Other Illusions about Testing by Gerald M. Weinberg

ISBN-10: 0932633692

ISBN-13: 978-0932633699

Rapid Development by McConnell

The most influential programming book for me was Enough Rope to Shoot Yourself in the Foot by Allen Holub.

Cover of the book

O, well, how long ago it was.

I have a few good books that strongly influenced me that I've not seen on this list so far:

The Psychology of Everyday Things by Donald Norman. The general principles of design for other people. This may seem to be mostly good for UI but if you think about it, it has applications almost anywhere there is an interface that someone besides the original developer has to work with; e. g. an API and designing the interface in such a way that other developers form the correct mental model and get appropriate feedback from the API itself.

The Art of Software Testing by Glen Myers. A good, general introduction to testing software; good for programmers to read to help them think like a tester i. e. think of what may go wrong and prepare for it.

By the way, I realize the question was the "Single Most Influential Book" but the discussion seems to have changed to listing good books for developers to read so I hope I can be forgiven for listing two good books rather than just one.

alt text

C++ How to Program It is good for beginner.This is excellent book that full complete with 1500 pages.

Effective C++ and More Effective C++ by Scott Myers.

Inside the C++ object model by Stanley Lippman

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

Not a programming book, but still a very important book every programmer should read:

Orbiting the Giant Hairball by Gordon MacKenzie

The Pragmatic programmer was pretty good. However one that really made an impact when I was starting out was :

Windows 95 System Programming Secrets"

I know - it sounds and looks a bit cheesy on the outside and has probably dated a bit - but this was an awesome explanation of the internals of Win95 based on the Authors (Matt Pietrek) investigations using his own own tools - the code for which came with the book. Bear in mind this was before the whole open source thing and Microsoft was still pretty cagey about releasing documentation of internals - let alone source. There was some quote in there like "If you are working through some problem and hit some sticking point then you need to stop and really look deeply into that piece and really understand how it works". I've found this to be pretty good advice - particularly these days when you often have the source for a library and can go take a look. Its also inspired me to enjoy diving into the internals of how systems work, something that has proven invaluable over the course of my career.

Oh and I'd also throw in effective .net - great internals explanation of .Net from Don Box.

I recently read Dreaming in Code and found it to be an interesting read. Perhaps more so since the day I started reading it Chandler 1.0 was released. Reading about the growing pains and mistakes of a project team of talented people trying to "change the world" gives you a lot to learn from. Also Scott brings up a lot of programmer lore and wisdom in between that's just an entertaining read.

Beautiful Code had one or two things that made me think differently, particularly the chapter on top down operator precedence.

K&R

@Juan: I know Juan, I know - but there are some things that can only be learned by actually getting down to the task at hand. Speaking in abstract ideals all day simply makes you into an academic. It's in the application of the abstract that we truly grok the reason for their existence. :P

@Keith: Great mention of "The Inmates are Running the Asylum" by Alan Cooper - an eye opener for certain, any developer that has worked with me since I read that book has heard me mention the ideas it espouses. +1

I found the The Algorithm Design Manual to be a very beneficial read. I also highly recommend Programming Pearls.

This one isnt really a book for the beginning programmer, but if you're looking for SOA design books, then SOA in Practice: The Art of Distributed System Design is for you.

For me it was Design Patterns Explained it provided an 'Oh that's how it works' moment for me in regards to design patterns and has been very useful when teaching design patterns to others.

Code Craft by Pete Goodliffe is a good read!

Code Craft

The first book that made a real impact on me was Mastering Turbo Assembler by Tom Swan.

Other books that have had an impact was Just For Fun by Linus Torvalds and David Diamond and of course The Pragmatic Programmer by Andrew Hunt and David Thomas.

In addition to other people's suggestions, I'd recommend either acquiring a copy of SICP, or reading it online. It's one of the few books that I've read that I feel greatly increased my skill in designing software, particularly in creating good abstraction layers.

A book that is not directly related to programming, but is also a good read for programmers (IMO) is Concrete Mathematics. Most, if not all of the topics in it are useful for programmers to know about, and it does a better job of explaining things than any other math book I've read to date.

For me "Memory as a programming concept in C and C++" really opened my eyes to how memory management really works. If you're a C or C++ developer I consider it a must read. You will defiantly learn something or remember things you might have forgotten along the way.

http://www.amazon.com/Memory-Programming-Concept-C/dp/0521520436

Agile Software Development with Scrum by Ken Schwaber and Mike Beedle.

I used this book as the starting point to understanding Agile development.

Systemantics: How Systems Work and Especially How They Fail. Get it used cheap. But you might not get the humor until you've worked on a few failed projects.

The beauty of the book is the copyright year.

Probably the most profound takeaway "law" presented in the book:

The Fundamental Failure-Mode Theorem (F.F.T.): Complex systems usually operate in failure mode.

The idea being that there are failing parts in any given piece of software that are masked by failures in other parts or by validations in other parts. See a real-world example at the Therac-25 radiation machine, whose software flaws were masked by hardware failsafes. When the hardware failsafes were removed, the software race condition that had gone undetected all those years resulted in the machine killing 3 people.

It seems most people have already touched on the some very good books. One which really helped me out was Effective C#: 50 Ways to Improve your C#. I'd be remiss if I didn't mention The Tao of Pooh. Philosophy books can be good for the soul, and the code.

Discrete Mathematics For Computer Scientists

Discrete Mathematics For Computer Scientists by J.K. Truss.

While this doesn't teach you programming, it teaches you fundamental mathematics that every programmer should know. You may remember this stuff from university, but really, doing predicate logic will improve you programming skills, you need to learn Set Theory if you want to program using collections.

There really is a lot of interesting information in here that can get you thinking about problems in different ways. It's handy to have, just to pick up once in a while to learn something new.

I saw a review of Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools on a blog talking also about XI-Factory, I read it and I must say this book is a must read. Altough not specifically targetted to programmers, it explains very clearly what is happening in the programming world right now with Model-Driven Architecture and so on..

Solid Code Optimizing the Software Development Life Cycle

Although the book is only 300 pages and favors Microsoft technologies it still offers some good language agnostic tidbits.

My vote is "How to Think Like a Computer Scientist: Learning With Python" It's available both as a book and as a free e-book.

It really helped me to understand the basics of not just Python but programming in general. Although it uses Python to demonstrate concepts, they apply to most, if not all, programming languages. Also: IT'S FREE!

Managing Gigabytes is an instant classic for thinking about the heavy lifting of information.

Object-Oriented Programming in Turbo C++. Not super popular, but it was the one that got me started, and was the first book that really helped me grok what an object was. Read this one waaaay back in high school. It sort of brings a tear to my eye...

My high school math teacher lent me a copy of Are Your Lights Figure Problem that I have re-read many times. It has been invaluable, as a developer, and in life generally.

I'm reading now Agile Software Development, Principles, Patterns and Practices. For those interested in XP and Object-Oriented Design, this is a classic reading.

alt text

Kernighan & Plauger's Elements of Programming Style. It illustrates the difference between gimmicky-clever and elegant-clever.

alt text

The Back of the Napkin, by Dan Roam.

The Back of the Napkin

A great book about visual thinking techniques. There is also an expanded edition now. I can't speak to that version, as I do not own it; yet.

to get advanced in prolog i like these two books:

The Art of Prolog

The Craft of Prolog

really opens the mind for logic programming and recursion schemes.

Here's an excellent book that is not as widely applauded, but is full of deep insight: Agile Software Development: The Cooperative Game, by Alistair Cockburn.

What's so special about it? Well, clearly everyone has heard the term "Agile", and it seems most are believers these days. Whether you believe or not, though, there are some deep principles behind why the Agile movement exists. This book uncovers and articulates these principles in a precise, scientific way. Some of the principles are (btw, these are my words, not Alistair's):

  1. The hardest thing about team software development is getting everyone's brains to have the same understanding. We are building huge, elaborate, complex systems which are invisible in the tangible world. The better you are at getting more peoples' brains to share deeper understanding, the more effective your team will be at software development. This is the underlying reason that pair programming makes sense. Most people dismiss it (and I did too initially), but with this principle in mind I highly recommend that you give it another shot. You wind up with TWO people who deeply understand the subsystem you just built ... there aren't many other ways to get such a deep information transfer so quickly. It is like a Vulcan mind meld.
  2. You don't always need words to communicate deep understanding quickly. And a corollary: too many words, and you exceed the listener/reader's capacity, meaning the understanding transfer you're attempting does not happen. Consider that children learn how to speak language by being "immersed" and "absorbing". Not just language either ... he gives the example of some kids playing with trains on the floor. Along comes another kid who has never even SEEN a train before ... but by watching the other kids, he picks up the gist of the game and plays right along. This happens all the time between humans. This along with the corollary about too many words helps you see how misguided it was in the old "waterfall" days to try to write 700 page detailed requirements specifications.

There is so much more in there too. I'll shut up now, but I HIGHLY recommend this book!

Agile Software Development by Alistair Cockburn

Do users ever touch your code? If you're not doing solely back-end work, I recommend About Face: The Essentials of User Interface Design — now in its third edition (linked). I used to think my users were stupid because they didn't "get" my interfaces. I was, of course, wrong. About Face turned me around.

"Writing Solid Code: Microsoft's Techniques for Developing Bug-Free C Programs (Microsoft Programming Series)" by Steve MacGuire.

Interesting what a large proportion the books mentioned here are C/C++ books.

While not strictly a software development book, I would highly recommend that Don't Make me Think! be considered in this list.

As so many people have listed Head First Design Patterns, which I agree is a very good book, I would like to see if so many people aware of a title called Design Patterns Explained: A New Perspective on Object-Oriented Design.

This title deals with design patterns excellently. The first half of the book is very accessible and the remaining chapters require only a firm grasp of the content already covered The reason I feel the second half of the book is less accessible is that it covers patterns that I, as a young developer admittedly lacking in experience, have not used much.

This title also introduces the concept behind design patterns, covering Christopher Alexander's initial work in architecture to the GoF first implementing documenting patterns in SmallTalk.

I think that anyone who enjoyed Head First Design Patterns but still finds the GoF very dry, should look into Design Patterns Explained as a much more readable (although not quite as comprehensive) alternative.

Even though i've never programmed a game this book helped me understand a lot of things in a fun way.

How influential a book is often depends on the reader and where they were in their career when they read the book. I have to give a shout-out to Head First Design Patterns. Great book and the very creative way it's written should be used as an example for other tech book writers. I.e. it's written in order to facilitate learning and internalizing the concepts.

Head First Design Patterns

97 Things Every Programmer Should Know

alt text

This book pools together the collective experiences of some of the world's best programmers. It is a must read.

Extreme Programming Explained: Embrace Change by Kent Beck. While I don't advocate a hardcore XP-or-the-highway take on software development, I wish I had been introduced to the principles in this book much earlier in my career. Unit testing, refactoring, simplicity, continuous integration, cost/time/quality/scope - these changed the way I looked at development. Before Agile, it was all about the debugger and fear of change requests. After Agile, those demons did not loom as large.

One of my personal favorites is Hacker's Delight, because it was as much fun to read as it was educational.

I hope the second edition will be released soon!

You.Next(): Move Your Software Development Career to the Leadership Track ~ Michael C. Finley (Author), Honza Fedák (Author) link text

I've been arounda while, so most books that I have found influential don't necessarily apply today. I do believe it is universally important to understand the platform that you are developing for (both hardware and OS). I also think it's important to learn from other peoples mistakes. So two books I would recommend are:

Computing Calamities and In Search of Stupidity: Over Twenty Years of High Tech Marketing Disasters

Working Effectively with Legacy Code is a really amazing book that goes into great detail about how to properly unit test your code and what the true benefit of it is. It really opened my eyes.

I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I'd like to ask how people have gone about testing code that relies on threads for successful execution, or just how people have gone about testing those kinds of issues that only show up when two threads interact in a given manner?

This seems like a really key problem for programmers today, it would be useful to pool our knowledge on this one imho.

Have a book at the book Clean Code CHAPTER 13 there is a whole section devoted there to testing multithreaded code and also to concurrency in general which might help you design better multithreaded code.

For Java, check out chapter 12 of JCIP. There are some concrete examples of writing deterministic, multi-threaded unit tests to at least test the correctness and invariants of concurrent code.

"Proving" thread-safety with unit tests is much dicier. My belief is that this is better served by automated integration testing on a variety of platforms/configurations.

Have a look at my related answer at

Designing a Test class for a custom Barrier

It's biased towards Java but has a reasonable summary of the options.

In summary though (IMO) its not the use of some fancy framework that will ensure correctness but how you go about designing you multithreaded code. Splitting the concerns (concurrency and functionality) goes a huge way towards raising confidence. Growing Object Orientated Software Guided By Tests explains some options better than I can.

Static analysis and formal methods (see, Concurrency: State Models and Java Programs) is an option but I've found them to be of limited use in commercial development.

Don't forget that any load/soak style tests are rarely guaranteed to highlight problems.

Good luck!

It is much more convenient and cleaner to use a single statement like

import java.awt.*;

than to import a bunch of individual classes

import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...

What is wrong with using a wildcard in the import statement?

It's not bad to use a wild card with a Java import statement.

In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.

Here is the recommendation:

J1: Avoid Long Import Lists by Using Wildcards

If you use two or more classes from a package, then import the whole package with

import package.*;

Long lists of imports are daunting to the reader. We don’t want to clutter up the tops of our modules with 80 lines of imports. Rather we want the imports to be a concise statement about which packages we collaborate with.

Specific imports are hard dependencies, whereas wildcard imports are not. If you specifically import a class, then that class must exist. But if you import a package with a wildcard, no particular classes need to exist. The import statement simply adds the package to the search path when hunting for names. So no true dependency is created by such imports, and they therefore serve to keep our modules less coupled.

There are times when the long list of specific imports can be useful. For example, if you are dealing with legacy code and you want to find out what classes you need to build mocks and stubs for, you can walk down the list of specific imports to find out the true qualified names of all those classes and then put the appropriate stubs in place. However, this use for specific imports is very rare. Furthermore, most modern IDEs will allow you to convert the wildcarded imports to a list of specific imports with a single command. So even in the legacy case it’s better to import wildcards.

Wildcard imports can sometimes cause name conflicts and ambiguities. Two classes with the same name, but in different packages, will need to be specifically imported, or at least specifically qualified when used. This can be a nuisance but is rare enough that using wildcard imports is still generally better than specific imports.

In DDD book

In whatever development technology the implementation will be based on, look for ways of minimizing the work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units while simultaneously reducing the effort of changing package names.

And if it clutters local namespace its not your fault - blame the size of the package.

Routines can have parameters, that's no news. You can define as many parameters as you may need, but too many of them will make your routine difficult to understand and maintain.

Of course, you could use a structured variable as a workaround: putting all those variables in a single struct and passing it to the routine. In fact, using structures to simplify parameter lists is one of the techniques described by Steve McConnell in Code Complete. But as he says:

Careful programmers avoid bundling data any more than is logically necessary.

So if your routine has too many parameters or you use a struct to disguise a big parameter list, you're probably doing something wrong. That is, you're not keeping coupling loose.

My question is, when can I consider a parameter list too big? I think that more than 5 parameters, are too many. What do you think?

In Clean Code, Robert C. Martin devoted four pages to the subject. Here's the gist:

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.

As we program, we all develop practices and patterns that we use and rely on. However, over time, as our understanding, maturity, and even technology usage changes, we come to realize that some practices that we once thought were great are not (or no longer apply).

An example of a practice I once used quite often, but have in recent years changed, is the use of the Singleton object pattern.

Through my own experience and long debates with colleagues, I've come to realize that singletons are not always desirable - they can make testing more difficult (by inhibiting techniques like mocking) and can create undesirable coupling between parts of a system. Instead, I now use object factories (typically with a IoC container) that hide the nature and existence of singletons from parts of the system that don't care - or need to know. Instead, they rely on a factory (or service locator) to acquire access to such objects.

My questions to the community, in the spirit of self-improvement, are:

  • What programming patterns or practices have you reconsidered recently, and now try to avoid?
  • What did you decide to replace them with?

Documenting the code with extensive inline code comments. Now I follow Uncle Bob's view that the code should be self-documenting: if you feel the need to write a comment about certain piece of code, you should refactor the code instead to make it more legible.

Also, code comments tend to get out of sync with the actual code they are supposed to describe. To quote Uncle: "the truth is in the code, not the comments".

Highly recommended book: Clean Code: A Handbook of Agile Software Craftsmanship

This is a situation I encounter frequently as an inexperienced programmer and am wondering about particularly for an ambitious, speed-intensive project of mine I'm trying to optimize. For the major C-like languages (C, objC, C++, Java, C#, etc) and their usual compilers, will these two functions run just as efficiently? Is there any difference in the compiled code?

void foo1(bool flag)
{
    if (flag)
    {
        //Do stuff
        return;
    }

    //Do different stuff
}

void foo2(bool flag)
{
    if (flag)
    {
        //Do stuff
    }
    else
    {
        //Do different stuff
    }
}

Basically, is there ever a direct efficiency bonus/penalty when breaking or returning early? How is the stackframe involved? Are there optimized special cases? Are there any factors (like inlining or the size of "Do stuff") that could affect this significantly?

I'm always a proponent of improved legibility over minor optimizations (I see foo1 a lot with parameter validation), but this comes up so frequently that I'd like to set aside all worry once and for all.

And I'm aware of the pitfalls of premature optimization... ugh, those are some painful memories.

EDIT: I accepted an answer, but EJP's answer explains pretty succinctly why the use of a return is practically negligible (in assembly, the return creates a 'branch' to the end of the function, which is extremely fast. The branch alters the PC register and may also affect the cache and pipeline, which is pretty minuscule.) For this case in particular, it literally makes no difference because both the if/else and the return create the same branch to the end of the function.

From Clean Code: A Handbook of Agile Software Craftsmanship

Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!

foo(true);

in code will just make the reader to navigate to the function and waste time reading foo(boolean flag)

Better structured code base will give you better opportunity to optimize code.

I've heard some voices saying that checking for a returned null value from methods is bad design. I would like to hear some reasons for this.

pseudocode:

variable x = object.method()
if (x is null) do something

Here's the reason.

In Clean Code by Robert Martin he writes that returning null is bad design when you can instead return, say, empty array. Since expected result is an array, why not? It'll enable you to iterate over result without any extra conditions. If it's an integer, maybe 0 will suffice, if it's a hash, empty hash. etc.

The premise is to not force calling code to immediately handle issues. Calling code may not want to concern itself with them. That's also why in many cases exceptions is better than nil.

I am a hobbyist programmer (started with VBA to make excel quicker) and have been working with VB.NET / C#.NET and am trying to learn ADO.NET. This is my first post and I apologise for the subjective nature of the question.

A facet of programming that has always frustrated me is what does 'good' look like? I am not a professional so have little to compare against. What makes a better programmer? Is it:

  • They have a better understanding of all the objects / classes / methods in a given language?
  • Their programs are more efficient?
  • The design of their programs are much better in terms of better documentation, good choice of names for functions etc.?

Put another way, if I were to look at the code of a professional programmer, what is the first thing that I would notice about their code relative to mine? For example, I read books like 'Professional ASP.NET' by Wrox press. Are the code examples in that book 'world class'? Is that the pinnacle? Would any top-gun programmer look at that code and think it was good code?

The list below is not comprehensive, but these are the things that I thought of in considering your question.

  • Good code is well-organized. Data and operations in classes fit together. There aren't extraneous dependencies between classes. It does not look like "spaghetti."

  • Good code comments explain why things are done not what is done. The code itself explains what is done. The need for comments should be minimal.

  • Good code uses meaningful naming conventions for all but the most transient of objects. the name of something is informative about when and how to use the object.

  • Good code is well-tested. Tests serve as an executable specification of the code and examples of its use.

  • Good code is not "clever". It does things in straightforward, obvious ways.

  • Good code is developed in small, easy to read units of computation. These units are reused throughout the code.

I haven't read it yet, but the book I'm planning to read on this topic is Clean Code by Robert C. Martin.

Read the book Code Complete. This explains a lot of ideas about how to structure code and the the reasons for doing so. Reading it should short-circuit your time to aquiring the experience necessary to tell good from bad.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1229267173&sr=8-1

i second the recommendation for uncle bob's "clean code". but you may wish to take a look at http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091 as i think this deals with your specific question a bit better. good code should leap off the page and tell you what it does/how it works.

Rather then repeat everyone else's great suggestions, I will instead suggest that you read the book Code Complete by Steve McConnell

Essentially it is a book packed full of programming best practices for both functionality and style.

I would like to know the basic principles and etiquette of writing a well structured code.

This list could go on for a long time but some major things are:

  • Indent.
  • Descriptive variable names.
  • Descriptive class / function names.
  • Don't duplicate code. If it needs duplication put in a class / function.
  • Use gettors / settors.
  • Only expose what's necessary in your objects.
  • Single dependency principle.
  • Learn how to write good comments, not lots of comments.
  • Take pride in your code!

Two good places to start:

Clean-Code Handbook

Code-Complete

How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?

Above answers all assume that the object in question is an object with behaviour. An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.

With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again. Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.

We follow Scrum for software development in our organization. Although we have fair experience with Scrum, we stop short of producing good source code at the end of the day. People are talking about combining Extreme Programming (XP) with Scrum to produce predictable results.

I have gone through the Extreme Programming materials but couldn't get a good picture.

How are Scrum and Extreme Programming are used in software development?

Both The Pragmatic Programmer (as mentioned by Jim Ferrans) and Clean Code are excellent resources for the agile programmer. You may also want to take a look at the books in the extreme programming series.

Does anyone happen to know what the maximum length of a method name is in your programming language of choice? I was going to make this a C# specific question, but I think it would be nice to know across the spectrum.

What are the factors involved as well:

  • Does the language specification limit this?
  • What does the compiler limit it to?
    • Is it different on 32bit vs 64bit machines?

Interesting! In Java as others said there is no limit (I never thought about the length!) but I think you want to avoid having a long method name as this could effect readability and even mental mapping (any other dev looking at the code may forget or want to forget the method name!).

I believe "clean code" in a nutshell talks about the use of descriptive pronounceable names. You could also argue a long descriptive name is better than a short one, I guess a sound balance. tis my humble view.

Possible Duplicate:
When is a function too long?

I've recently been given the unenviable task of reviewing poor code written by another developer and documenting the bad practices. (This is all for the purposes of getting out of paying for the developer's work rather than any altruistic reason, of course!)

The reviewed code has several procedures that are many lines of code - the longest is almost 600 lines. A couple of problems with this that I've thought of are maintainability and readability.

The trick is that I need to justify to a layperson why this is a bad practice and if possible back it up with a well regarded and current reference book. Analogies are good too.

Any ideas?

Duplicate: When is a function too long?
Duplicate: Best rule for maximum function size?

It's not about lines of code. As Steve Mcconnell and Bob Martin say (two pretty good references on coding best practices), a method should do one thing and only one thing. However many lines of code it takes to do that one thing is how many lines it should have. If that "one thing" can be broken into smaller things, each of those should have a method.

Good clues your method is doing more than one thing:

  • More than one level of indention in a method (indicates too many logic branches to only be doing one thing)
  • "Paragraph Breaks" - whitespace between logical groups of code indicate the method is doing more than one thing

Just to name a few. Bob Martin also says to keep it around 10. Personally I usually try to shoot for 10. If it starts getting close to 20, that's a mental flag to pay closer attention to that method. But ultimately, LoC is a bad metric for pretty much anything. It is only a helpful indicator that can potentially point to the real issue.

I've already awarded a 100 point bounty to mario's answer, but might start a second 100 point bounty if I see new good answers coming in. This is why I'm keeping the question open and will not choose a final answer, despite having awarded the bounty to mario.

This might seem like a simple question (study the code and refactor) but I'm hoping those with lots more experience can give me some solid advice.

The library is an open source 20,000 line library that's all in a single file and which I haven't written myself. The code looks badly written and the single file is even a bigger problem, because it freezes eclipse for half a minute at least every time I want to make a change, which is one of the reasons I think it's worth it to refactor this library into smaller classes.

So aside from reading the code and trying to understand it, are there common (or not so common) tips when refactoring a library such as this? What do you advise to make my life a little easier?

Thanks to everyone for your comments.

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Refactoring depends from you goals and type of solution. This book will help you to understand basic concepts of right code.

Let's say we have CQRS-inspired architecture, with components such as Commands, Domain Model, Domain Events, Read Model DTOs.
Of course, we can use Value Objects in our Domain Model. My question is, should they also be used in:

  1. Commands
  2. Events
  3. DTOs

I haven't seen any examples where Value Objects (VO) are used in the components mentioned above. Instead, primitive types are used. Maybe it's just the simplistic examples. After all, my understanding of VOs use in DDD is that they act as a glue for the whole application.

My motivation:

Commands.
Let's say user submits a form which contains address fields. We have Address Value Object to represent this concept. When constructing command in the client, we should validate user input anyway, and when it is well-formed, we can create Address object right there and initialize Command with it. I see no need to delegate creation of Address object to command handler.

Domain Events.
Domain Model already operates in terms of Value Objects, so by publishing events with VOs instead of converting them to primitive types, we can avoid some mapping code. I'm pretty sure it's alright to use VOs in this case.

DTOs.
If our query-side DTOs can contain Value Objects, this allows for some more flexibility. E.g., if we have Money object, we can choose whether to display it in EUR or USD, no need to change Read Model.

According to Clean Code your DTOs are data structures (just to add another term), while value objects are objects. The difference that objects can have behavior. Mixing data structures with objects is generally a very bad idea, because it will be hard to maintain the hybrid you get.

I don't feel right to put value objects to DTOs from an architecture perspective as well. The value objects are inside of the domain model while the DTOs you mentioned are defining the interface of the model. We usually build an interface to decouple the outside world from the inside of something. So in the current case we added DTOs to decouple the outside world from the value objects (and other model related stuff). After that adding value objects to the interface is crazy.

So you haven't met this solution yet because it is an anti-pattern.

I do write unit tests while writing APIs and core functionalities. But I want to be the cool fanboy who eats, sleeps and breathes TDD and BDD. What's the best way to get started with TDD/BDD the right way? Any books, resources, frameworks, best practices?

My environment is Java backend with Grails frontend, integrated with several external web services and databases.

A good place to start is reading blogs. Then buy the books of the people who are blogging. Some I would highly recommend:

"Uncle Bob" Martin and the guys at Object Mentor: http://blog.objectmentor.com/

P.S. get Bobs book Clean Code:

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

My friend Tim Ottinger (former Object Mentor dude) http://agileinaflash.blogspot.com/ http://agileotter.blogspot.com/

The Jetbrains guys: http://www.jbrains.ca/permalink/285

I felt the need to expand on this, as everyone else seems to just want to give you their opinion of TDD and not help you on your quest to become a Jedi-Ninja. The Michael Jordan of TDD is Kent Beck. He really did write the book on it:

http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530

he also blogs at:

http://www.threeriversinstitute.org/blog/?p=29

other "famous" supporters of TDD include:

All are great people to follow. You should also consider attending some conferences like Agile 2010, or Software Craftsmanship (this year they were held at the same time in Chicago)

I've been doing TDD for a couple of years, but lately I've started looking more in to the BDD way of driving my design and development. Resources that helped me get started on BDD was first and formost Dan North's blog (the 'founder' of BDD). Take a look at Introducing BDD. There's also an 'official' BDD Wiki over at behaviour-driven.org with some good post well worth reading.

The one thing that I found really hard when starting out with BDD (and still find a bit hard) is how to formulate those scenarios to make them suitable to BDD. Scott Bellware is a man well skilled in BDD (or Context-Spesification as he like to coin it) and his article Behavior-Driven Development in Code Magazine helped me a lot on understanding the BDD way of thinking and formulating user stories.

I would also recomend the TekPub screencast Behavior-driven Design with Specflow by Rob Conery. A great intro to BDD and to a tool (SpecFlow) very good suited for doing BDD in C#.

As for TDD resources, there's already a lot of good recommendations here. But I just want to point out a couple of books that I can really recommend;

In your experience, what are some "smelly" keywords in class or function names that might be warning signs of bad object-oriented design?

I've found that classes containing the word Manager or Base are often suspect. For example, a FooManger often indicates poor encapsulation or a singleton design that is difficult to reuse.

A FooBase class is typically an abstract base class that is never expected to be directly referenced in caller code. It's only used to share some code implementation without a true IS-A relationship. And the Base class name exposes internal implementation details and does not reflect a "real world" object in a Domain Model.

Functions that include the word And or Or (e.g. DoThisAndThat() or DoThisOrThat()) are smelly. The function is probably lack cohesion and is trying to do too much. And the name exposes internal implementation details.

I've found this to be helpful:

"Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb."

(From Clean Code by Robert Martin, p25)

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out within a class?

A : 1) public methods 2) private methods 3) public vars 4) private vars

B : 1) public vars 2) private vars 3) public methods 4) private methods

C : 1) public vars 2) public methods 3) private methods 4)private vars

I generally like to put public static vars at the top, but then would a public static method be listed ahead of your constructor, or should the constructor always be listed first? That sort of thing...

I know it's finnicky but I just wondered: what are best practices for this?

PS: no I don't use Cc#. I know. I'm a luddite.

In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much. This is a more sensible way to organize code rather than by access modifier.

I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time.

One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using issubclass in each method doesn't sound very tempting either.

My preferred way is to use the object in good faith, but this will raise some AttributeErrors. I could wrap each dangerous call in a try/except block. This, too, seems kind of cumbersome:

def foo(obj):
    ...
    # it should be able to sleep
    try:
        obj.sleep()
    except AttributeError:
        # handle error
    ...
    # it should be able to wag it's tail
    try:
        obj.wag_tail()
    except AttributeError:
        # handle this error as well

Should I just skip the error handling and expect people to only use objects with the required methods? If I do something stupid like [x**2 for x in 1234] I actually get a TypeError and not a AttributeError (ints are not iterable) so there must be some type checking going on somewhere -- what if I want to do the same?

This question will be kind of open ended, but what is the best way to handle the above problem in a clean way? Are there any established best practices? How is the iterable "type checking" above, for example, implemented?

Edit

While AttributeErrors are fine, the TypeErrors raised by native functions usually give more information about how to solve the errors. Take this for example:

>>> ['a', 1].sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

I'd like my library to be as helpful as possible.

I'm not a python pro but I believe that unless you can try an alternative for when the parameter doesn't implement a given method, you shoudn't prevent exceptions from being thrown. Let the caller handle these exceptions. This way, you would be hidding problems from the developers.

As I have read in Clean Code, if you want to search for an item in a collection, don't test your parameters with ìssubclass (of a list) but prefer to call getattr(l, "__contains__"). This will give someone who is using your code a chance to pass a parameter that isn't a list but which has a __contains__ method defined and things should work equally well.

So, I think that you should code in an abstract, generic way, imposing as few restrictions as you can. For that, you'll have to make the fewest assumptions possible. However, when you face something that you can't handle, raise an exception and let the programmer know what mistake he made!

The commonly accepted way to format C# code seems to be as follows:

namespace SomeNamespace
{
    namespace SomeSubNamespace
    {
        class SomeClass
        {
            void SomeFunction()
            {
                using (var someFile = new StreamWriter(somePath))
                {
                    try
                    {
                        lock(someCriticalSection)
                        {
                            using (var someDisposableThing1 = new DisposableThing())
                            {
                                DoSomething();                            
                                using (var someDisposableThing2 = new DisposableThing())
                                {
                                    lock(someOtherCriticalSection)
                                    {
                                        DoSomethingMore();
                                    }
                                }
                            }
                        }
                    }
                    catch(Exception e)
                    {
                        Log(e);
                    }
            }
        }
    }
}

This wastes a large amount of screen space, both horizontally and vertically. I'm surely not the first person who notices. My question is: do you live with it, or have you developed a different formatting style to avoid an excess of white space?

PS: Note that I didn't even use a single if statement yet!

You should read Bob Martin's Clean Code. It helps with this problem. In this instance, SomeFunction() does more than one thing. Split out each thing it does in its own method.

 namespace SomeNamespace.SomeSubNamespace
 {
    class SomeClass
    {
        void WriteToFile()
        {
            using (var someFile = new StreamWriter(somePath))
            {
                lock(someCriticalSection)
                {
                   ExecuteCriticalSection();
                }
            }
        }
        void ExecuteCriticalSection()
        {
            using (var someDisposableThing1 = new DisposableThing())
            {
            DoSomething();
            ExecuteFinalCriticalSection();
            }   
        }

        void ExecuteFinalCriticalSection()
        {
            using (var someDisposableThing2 = new DisposableThing())
            {
            lock(someOtherCriticalSection)
                {
                DoSomethingMore();
                }
            }
        }
    }
}

Also, don't catch a System.Exception; you never know what's going to fail, and you shouldn't try to catch exceptions you can't handle. Let them bubble up and die horribly.

Intent

I am looking for the following:

  • A solid unit testing methodology
    1. What am I missing from my approach?
    2. What am I doing wrong?
    3. What am I doing which is unnecessary?
  • A way to get as much as possible done automatically

Current environment

  • Eclipse as IDE
  • JUnit as a testing framework, integrated into Eclipse
  • Hamcrest as a "matchers" library, for better assertion readability
  • Google Guava for precondition validation

Current approach

Structure

  • One test class per class to test
  • Method testing grouped in static nested classes
  • Test method naming to specify behaviour tested + expected result
  • Expected exceptions specified by Java Annotation, not in method name

Methodology

  • Watch out for null values
  • Watch out for empty List<E>
  • Watch out for empty String
  • Watch out for empty arrays
  • Watch out for object state invariants altered by code (post-conditions)
  • Methods accept documented parameter types
  • Boundary checks (e.g. Integer.MAX_VALUE, etc...)
  • Documenting immutability through specific types (e.g. Google Guava ImmutableList<E>)
  • ... is there a list for this? Examples of nice-to-have testing lists:
    • Things to check in database projects (e.g. CRUD, connectivity, logging, ...)
    • Things to check in multithreaded code
    • Things to check for EJBs
    • ... ?

Sample code

This is a contrived example to show some techniques.


MyPath.java

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Arrays;
import com.google.common.collect.ImmutableList;
public class MyPath {
  public static final MyPath ROOT = MyPath.ofComponents("ROOT");
  public static final String SEPARATOR = "/";
  public static MyPath ofComponents(String... components) {
    checkNotNull(components);
    checkArgument(components.length > 0);
    checkArgument(!Arrays.asList(components).contains(""));
    return new MyPath(components);
  }
  private final ImmutableList<String> components;
  private MyPath(String[] components) {
    this.components = ImmutableList.copyOf(components);
  }
  public ImmutableList<String> getComponents() {
    return components;
  }
  @Override
  public String toString() {
    StringBuilder stringBuilder = new StringBuilder();
    for (String pathComponent : components) {
      stringBuilder.append("/" + pathComponent);
    }
    return stringBuilder.toString();
  }
}

MyPathTests.java

import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.base.Joiner;
@RunWith(Enclosed.class)
public class MyPathTests {
  public static class GetComponents {
    @Test
    public void componentsCorrespondToFactoryArguments() {
      String[] components = { "Test1", "Test2", "Test3" };
      MyPath myPath = MyPath.ofComponents(components);
      assertThat(myPath.getComponents(), contains(components));
    }
  }
  public static class OfComponents {
    @Test
    public void acceptsArrayOfComponents() {
      MyPath.ofComponents("Test1", "Test2", "Test3");
    }
    @Test
    public void acceptsSingleComponent() {
      MyPath.ofComponents("Test1");
    }
    @Test(expected = IllegalArgumentException.class)
    public void emptyStringVarArgsThrows() {
      MyPath.ofComponents(new String[] { });
    }
    @Test(expected = NullPointerException.class)
    public void nullStringVarArgsThrows() {
      MyPath.ofComponents((String[]) null);
    }
    @Test(expected = IllegalArgumentException.class)
    public void rejectsInterspersedEmptyComponents() {
      MyPath.ofComponents("Test1", "", "Test2");
    }
    @Test(expected = IllegalArgumentException.class)
    public void rejectsSingleEmptyComponent() {
      MyPath.ofComponents("");
    }
    @Test
    public void returnsNotNullValue() {
      assertThat(MyPath.ofComponents("Test"), is(notNullValue()));
    }
  }
  public static class Root {
    @Test
    public void hasComponents() {
      assertThat(MyPath.ROOT.getComponents(), is(not(empty())));
    }
    @Test
    public void hasExactlyOneComponent() {
      assertThat(MyPath.ROOT.getComponents(), hasSize(1));
    }
    @Test
    public void hasExactlyOneInboxComponent() {
      assertThat(MyPath.ROOT.getComponents(), contains("ROOT"));
    }
    @Test
    public void isNotNull() {
      assertThat(MyPath.ROOT, is(notNullValue()));
    }
    @Test
    public void toStringIsSlashSeparatedAbsolutePathToInbox() {
      assertThat(MyPath.ROOT.toString(), is(equalTo("/ROOT")));
    }
  }
  public static class ToString {
    @Test
    public void toStringIsSlashSeparatedPathOfComponents() {
      String[] components = { "Test1", "Test2", "Test3" };
      String expectedPath =
          MyPath.SEPARATOR + Joiner.on(MyPath.SEPARATOR).join(components);
      assertThat(MyPath.ofComponents(components).toString(),
          is(equalTo(expectedPath)));
    }
  }
  @Test
  public void testPathCreationFromComponents() {
    String[] pathComponentArguments = new String[] { "One", "Two", "Three" };
    MyPath myPath = MyPath.ofComponents(pathComponentArguments);
    assertThat(myPath.getComponents(), contains(pathComponentArguments));
  }
}

Question, phrased explicitly

  • Is there a list of techniques to use to build a unit test? Something much more advanced than my oversimplified list above (e.g. check nulls, check boundaries, check expected exceptions, etc.) perhaps available in a book to buy or a URL to visit?

  • Once I have a method that takes a certain type of parameters, can I get any Eclipse plug-in to generate a stub for my tests for me? Perhaps using a Java Annotation to specify metadata about the method and having the tool materialise the associated checks for me? (e.g. @MustBeLowerCase, @ShouldBeOfSize(n=3), ...)

I find it tedious and robot-like to have to remember all of these "QA tricks" and/or apply them, I find it error-prone to copy and paste and I find it not self-documenting when I code things as I do above. Admittedly, Hamcrest libraries go in the general direction of specialising types of tests (e.g. on String objects using RegEx, on File objects, etc) but obviously do not auto-generate any test stubs and do not reflect on the code and its properties and prepare a harness for me.

Help me make this better, please.

PS

Do not tell me that I am just presenting code which is a silly wrapper around the concept of creating a Path from a list of path steps supplied in a static factory method please, this is a totally made-up example but it shows a "few" cases of argument validation... If I included a much longer example, who would really read this post?

  1. Consider using ExpectedException instead of @Test(expected.... This is because if for example you expect a NullPointerException and your test throws this exception in your setup (before calling the method under test) your test will pass. With ExpectedException you put the expect immediately before the call to the method under test so there is no chance of this. Also, ExpectedException allows you to test the exception message which is helpful if you have two different IllegalArgumentExceptions that might be thrown and you need to check for the correct one.

  2. Consider isolating your method under test from the setup and verify, this will ease in test review and maintenance. This is especially true when methods on the class under test are invoked as part of setup which can confuse which is the method under test. I use the following format:

    public void test() {
       //setup
       ...
    
       // test (usually only one line of code in this block)
       ...
    
       //verify
       ...
    }
    
  3. Books to look at: Clean Code, JUnit In Action, Test Driven Development By Example

    Clean Code has an excellent section on testing

  4. Most example I have seen (including what Eclipse autogenerates) have the method under test in the title of the test. This facilitates review and maintenance. For example: testOfComponents_nullCase. Your example is the first I have seen that uses the Enclosed to group methods by method under test, which is really nice. However, it adds some overhead as @Before and @After do not get shared between enclosed test classes.

  5. I have not started using it, but Guava has a test library: guava-testlib. I have not had a chance to play with it but it seems to have some cool stuff. For example: NullPointerTest is quote:

  • A test utility that verifies that your methods throw {@link * NullPointerException} or {@link UnsupportedOperationException} whenever any * of their parameters are null. To use it, you must first provide valid default * values for the parameter types used by the class.

Review: I realize the test above was just an example but since a constructive review might be helpful, here you go.

  1. In testing getComponents, test the empty list case as well. Also, use IsIterableContainingInOrder.

  2. In testing of ofComponents, it seems that it would make sense to call getComponents or toString to validate that it properly handled the various non-error cases. There should be a test where no argument is passed to ofComponents. I see that this is done with ofComponents( new String[]{}) but why not just do ofComponents()? Need a test where null is one of the values passed: ofComponents("blah", null, "blah2") since this will throw an NPE.

  3. In testing ROOT, as has been pointed out before, I suggest calling ROOT.getComponents once and doing all three verifications on it. Also, ItIterableContainingInOrder does all three of not empty, size and contains. The is in the tests is extraineous (although it is linguistic) and I feel is not worth having (IMHO).

  4. In testing toString, I feel it is very helpful to isolate the method under test. I would have written toStringIsSlashSeparatedPathOfComponents as follows. Notice that I do not use the constant from the class under test. This is because IMHO, ANY functional change to the class under test should cause the test to fail.

    @Test     
    public void toStringIsSlashSeparatedPathOfComponents() {       
       //setup 
       String[] components = { "Test1", "Test2", "Test3" };       
       String expectedPath =  "/" + Joiner.on("/").join(components);   
       MyPath path = MyPath.ofComponents(components)
    
       // test
       String value = path.toStrign();
    
       // verify
       assertThat(value, equalTo(expectedPath));   
    } 
    
  5. Enclosed will not run any unit test that is not in an inner class. Therefore testPathCreationFromComponents would not be run.

Finally, use Test Driven Development. This will ensure that your tests are passing for the right reason and will fail as expected.

Are there any (static analysis / refactoring / ...) tools for Java specially tailored towards clean code development (CCD)?

I know of the usual tools for static analysis (PMD, Findbugs, Checkstyle), dependency injection, testing and code coverage. But I am looking for a tool that gives me hints how clean my code is (as described e.g. here and in Uncle Bob's Clean Code), how I can make it cleaner, preferably attuned to my clean code grade. A tool that could also show me how I am improving in CCD over time would be optimal.

An example of such a tool is CcdAddIn, which displays the CCD values according to your current CCD Grade, but its only for visual studio :(

So do you know such tools for Java? Which one is best? What of the above do they fulfill? Or do you have a reason why such a tool does not exist (yet)?


If you do not know of such a tool: Do you know of a static analysis tool that can be configured to check for the criteria given in Uncle Bob's Clean Code, e.g. warn me about smells like names or comments seeming to be chosen badly, methods that are too long or have too many parameters, and immediately suggest a particular refactoring to resolve this?

Sonar comes preset with some decent code quality profiles--based on PMD, Checkstyle, and Findbugs--and a nice interface for customizing them for your own use. I don't think you're going to find one, universal list of "Thou shalt..." in the Java world. There are too many different applications and development approaches for that kind of uniformity. If you take a look at the predefined PMD rule sets, you'll even find a set of "Controversial Rules" which are specifically ones that tend to engender heated debates. Some love them; some hate them. So the first moral here would be to use established conventions as guidelines and add/remove as you see fit.

I've never heard of CCD in Java land, so I wouldn't expect to find a direct translation. If you care about healthy (clean?) code, you must use a tool like Sonar or else all of the tools that it compiles into one, convenient interface. Sonar does much more than just the static analysis. There's a demo instance of Sonar where you can get an idea of its features as well as recoil in horror at the metrics of some open source libraries. So the second moral would be, "Use Sonar because it's awesome."

I can't decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor at least you enforce that all the fields are set. Java Beans easier to see which variables are being set instead of a huge list. The builder pattern DOES NOT seem suitable here as all the fields are mandatory and the builder requires you put all mandatory parameters in the builder constructor.

Thanks, D

In his book Code Complete, Steve McConnell argues that no procedure should ever have more than a maximum of 6, maybe 7 arguments. Most of these statements are not just his opinion but backed by studies, e.g. of error rates related to code structure.

Clean Code by Robert Martin goes even further: He recommends 1 or 2 arguments, while 3 is already considered a "code smell". Personally, I think Clean Code is a bit extreme in places, but on the whole it makes some good arguments.

"A whole bunch of parameters" (however many that may be) bespeaks a "kitchen sink" design with lots of afterthoughts and little structure. It also makes maintenance more difficult and error prone; at the very least, it makes code hard to read.

All this makes for good reasons to think about cutting down on the number of parameters. Other answers have offered some practical suggestions.

Ultimately, code compiles down (eventually) into instructions for a CPU. Code, however, (in my humble opinion) is for human beings to read, update, and interact with. This leads me to the following observation:

Code that is unreadable by other engineers, even if it's functional, is bad code.

With that in mind, what can this programmer do to make code more easily read by humans?

  • Naming Conventions? (Joel has a fair amount to say on that one)

  • Code Structure/Layout? (please, for the love of god, don't get into the { placement debate)

  • Phrasing? (Is it possible to write code that looks more like the English language)

Are there good articles out there beyond Joel's.

I would recommend taking a look at Clean Code by Robert Martin. It's a great guide on how to make your code more readable and, well, clean.

I tend to create very large classes that have 30-40 (or more) methods. How many methods are too many? Are there any "smells" or rules of thumb to use?

As others have said, a class is too big when it is trying to do more than one thing and violates the Single Responsibility Principle.

An excellent book on this and other topics (and one I strongly recommend for any developer) is Clean Code by Bob Martin.

Is it a best practice to put Javadoc comments in junit test classes and methods? Or is the idea that they should be so easy to read and simple that it is unnecessary to provide a narrative of the test intent?

I personally use javadoc comments sparingly as I find they increase the on-screen clutter. If I can name a class, function or variable in a more self-descriptive way then I will in preference to a comment. An excellent book to read on this topic is Clean Code by Robert C. Martin (a.k.a Uncle Bob).

My personal preference is to make both the class and methods self descriptive i.e.

class ANewEventManager {
   @Test
   public void shouldAllowClassesToSubscribeToEvents() {
        /* Test logic here */
   }
}

One advantage of this approach is that it is easy to see in the junit output what is failing before browsing the code.

Just found StyleCop, looks like something worth using for my projects. Then I found out you could use it with ReSharper (a tool I've also never used). So I downloaded ReSharper, as well as StyleCop for ReSharper. I'm just a bit confused about it, though:

  1. With just StyleCop installed (no ReSharper), I get yelled at for referring directly to private variables in code-behind. It wants me to instead do this.variable. Alright, fine.

  2. If I use just ReSharper, it tells me to remove all of the 'this' calls I just added. Which one is better?

  3. If I use ReSharper + StyleCop for ReSharper, it now tells me to add 'this' to all private member references (just like StyleCop did all by itself). However, now it also wants me to add 'this' to all of the controls I'm referencing from the .aspx page (i.e., Label.Text = this.variable -> this.Label.Text = this.variable).

I'm so confused. What is the best standard to follow? Or am I just fine doing it the way I am now (Label.Text = variable)?

Sorry when working on a team it all comes down to understanding the politics; after all, we work to get paid!

If the person that decided your next pay raise uses StyleCop, then you should always include the “this.” likewise if the boss uses ReSharper you should do what ReSharper says.

There are a lot more important wars to win this, e.g. 10,000 line classes, over sized method

If you are luckly enough to decide what tools (and coding standards) are used yourself, then I would just choose ReSharper and read the “clean code” book.

When is a function too long? is a subset of this question, I think.

What are a few good metrics for determining that a class is too long?

I'm rerevising a set of code acceptance guidelines for a project with external contractors, and realized I haven't covered this in the past, but should cover this in the future.

When it has more than one responsibility.

Let me quote Robert C. Martin's Clean Code here:

The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. ... With functions we measured size by counting physical lines. With classes we use a different measure. We count responsibilities. [Chapter 10, page 136]

I hope this isn't a duplicate...

What is the most solidly designed and implemented software system/framework/application that you've come across?

It seems like TDD, SOLID principles, OO design patterns, and things like that can be easily theorized on podcasts and blogs using really simple examples, but it's hard to imagine developing large systems that fully live up to these standards, without an explosion of code. At my company, doing full TDD seems almost out of the question with our time constraints.

If anyone can point me to any good open-source projects, I'd really like to dig in and see what good TDD/SOLID/etc. looks like. Thanks.

Many of the other posts mention programs, which have not been implemented with TDD, and as such do not give an answer to "I'd really like to dig in and see what good TDD/SOLID/etc. looks like." For example, I'm quite positive that the sources of Apache HTTPD Server and Firefox have never even seen TDD. I just browsed a little their sources, and there were only a couple of small files in the test folders, and the production code didn't look like it was written with TDD or by following SOLID either.

For example Fitnesse has been written using TDD by the inventor of SOLID. That should be a good reference of what such code looks like, especially the newer parts of the code (in his book Clean Code, Uncle Bob has some examples of bad code from Fitnesse, which he then cleans up, so not necessarily all code in Fitnesse is clean).

I'll also throw in my own project, Dimdwarf Application Server, which has been written 100% with TDD/BDD and by trying to write as clean code as possible (following SOLID etc.). There are some ugly parts there as well (mostly in task scheduling and garbage collection), but those parts are still under work and they will be cleaned up by the time those features are complete.

I've seen a trend to move business logic out of the data access layer (stored procedures, LINQ, etc.) and into a business logic component layer (like C# objects).

Is this considered the "right" way to do things these days? If so, does this mean that some database developer positions may be eliminated in favor of more middle-tier coding positions? (i.e. more c# code rather than more long stored procedures.)

If the applications is small with a short lifetime, then it's not worth putting time into abstracting the concerns in layers. In larger, long lived applications your logic/business rules should not be coupled to the data access. It creates a maintenance nightmare as the application grows.

Moving concerns to a common layer or also known as Separation of concerns, has been around for a while:

Wikipedia

The term separation of concerns was probably coined by Edsger W. Dijkstra in his 1974 paper "On the role of scientific thought"1.

For Application Architecture a great book to start with is Domain Driven Design. Eric Evans breaks down the different layers of the application in detail. He also discusses the database impedance and what he calls a "Bounded Context"

Bounded Context

A blog is a system that displays posts from newest to oldest so that people can comment on. Some would view this as one system, or one "Bounded Context." If you subscribe to DDD, one would say there are two systems or two "Bounded Contexts" in a blog: A commenting system and a publication system. DDD argues that each system is independent (of course there will be interaction between the two) and should be modeled as such. DDD gives concrete guidance on how to separate the concerns into the appropriate layers.

Other resources that might interest you:

Until I had a chance to experience The Big Ball of Mud or Spaghetti Code I had a hard time understanding why Application Architecture was so important...

The right way to do things will always to be dependent on the size, availability requirements and lifespan of your application. To use stored procs or not to use stored procs... Tools such as nHibrnate and Linq to SQL are great for small to mid-size projects. To make myself clear, I've never used nHibranate or Linq To Sql on a large application, but my gut feeling is an application will reach a size where optimizations will need to be done on the database server via views, Stored Procedures.. etc to keep the application performant. To do this work Developers with both Development and Database skills will be needed.

What is the most useful/most standard/least surprising way to consistently write comment blocks for constructors and classes and files containing just a single class?

  • Comment blocks for classes, not constructors
  • Comment blocks for constructors, not classes
  • Comment blocks for both constructors and classes -> In that case what sort of details should go in each?

And then the file itself? Does this need a comment block if it just contains a single class? What details should go there?

I want to try and avoid, as much as possible, repetition between class, constructor and file comment blocks.

This is highly depending on your context and the assumed skill level of the people youu work with or the people that come after you.

If you publish a framework, a library or something of the sort you usually assume that your user are of all skill levels so you might want to document as much trivial crap as possible to reduce the load of questions your community has to handle.

Let me start of with an example where I think documentation can be a major pain.

What do you absolutly need

If you want to use PHPDoc you need a file doc block and another doc block after that (usually the class doc block).

Those **need* to have a @package Tag. Everything else is optional.

I'd go so far and say that even the @package Tag is optional since you might be albe to automatically generate it for project. And if i remember correctly PHPDoc lets you even set a default package for everything that doesn't have a tag.

For documentation in general let me start of with an example (a longer example is at the end):

How many times can you explain what "uri" means:

Massive docs Note that for getUri it is explained what URI stands for (just to have something to talk about in the comment I'd assume) while it isn't in isAbsUri because there you can at least say "abs means absolute" twice.


If you are not an open source project (or need to ship COMPLETE!!!11eleven api documentation):

I'd strongly suggest to use proper, long and descriptive class, variable and method names instead of documentation.

There is no gain in writing something again in the doc blocks and since it is 2011 and we have 120 char wide terminals and autocompletion there is just no need anymore to abbreviate everything for the sake of saving some chars.

I'd even argue that documenting trivial things hurts you and your team by forcing you to waste time on things nobody gets value from you get into a habit of always writing trivial docs and not reading them anymore.

A good comment should explain WHY something was done while the code its self should explain HOW without needing further comments.

My favorite example for redundant docs is this one:

class myClass {
/**
 * Constructor
 */
public function __construct() {
}

Some guidelines say you HAVE to document EVERYTHING and you end up with people stating the obvious again and again.

This adds no value but wastes time when reading the code.

An example for proper naming:

class Person { 
/** 
 * Set a persons weight in Kilogram
 *
 * @param float $kg Weight in Kilogram
 */
public function setWeight($kg) {}

This code is easy to document because you need to explain what "kg" means because some people might use a different system and you can't google for "kg".

I'm in favor of writing

class Person { 
/** 
 * @param float $kilogram
 */
public function setWeight($kilogram) {}

The doc block is superfluous because calling setWeight on Person can REALLY be expected to set the Weight on a Person. No need to write that out again.

Using $kilogramm as a parameter also saves you the trouble of explaining it in the docs and I'd say, depending on your environment, everyone can be expected to google for "kilogram" if he really doesn't know the measurement unit.


@PHPDoc documentation

  • All my humble opinion of course
  • If you don't use type-hinting always use @param tags.
  • Always use @return tags
  • Don't use @author tags at all. Collection code ownership is more valuable and the information is in the source control repository anyways.
  • Only use @copyright tags if you have to. I like only having a LICENSE file but I'm not a lawyer so it might be necessary.

Inline comments:

public function generateReport() {
  // get the db connection
  $reg = WhateverGlobalStorage::get(“db“);
  // auth
  if(!$reg->getOne("SELECT view_report FROM USER ...")) {}
  // template
  $id = $reg->getOne("select ... "); 
  // render
  new ReportTemplate($id); // ...
}

If those are separate "blocks" just move them to descriptive named functions

public function generateReport() {
  $this->checkAuthentication();
  $template = this->createReportTemplate();
  $this->renderReport($template);
}
// Not perfect but at least you can grasp what the method does much quicker

Additional resources:

Slides of a presentation I gave on the subject on some conferences: Slideshare: clean-code-stop-wasting-my-time

And additional small, little older, rant: they-told-you-to-document-everything-they-lied

Book references:

Clean Code - Cover Clean Code: A Handbook of Agile Software Craftsmanship

Refactoring - Cover Refactoring: Improving the Design of Existing Code

A longer example

abstract class xyzRequest {
 /**
   * Initializes this xyzRequest.
   *
   * Available options:
   *
   *  * logging: Whether to enable logging or not (false by default)
   *
   * @param  xyzEventDispatcher $dispatcher  An xyzEventDispatcher instance
   * @param  array  $parameters  An associative array of initialization parameters
   * @param  array  $attributes  An associative array of initialization attributes
   * @param  array  $options     An associative array of options
   *
   * @return bool true, if initialization completes successfully, otherwise false
   *
   * @throws <b>xyzInitializationException</b> If an error occurs while initializing this xyzRequest
   */
  public function initialize(xyzEventDispatcher $dispatcher, $parameters = array(), $attributes = array(), $options = array()) {

Lets see, line by line, what that documentation tells you. (I'm joking around here a little bit to get my point across)

* Initializes this xyzRequest.

So calling ->initialize on a xyzRequest initializes that request? Really? Ok then, if you say so!

   * Available options:
   *
   *  * logging: Whether to enable logging or not (false by default)

We are told the options for the third parameter, not for the second or third param but maybe we know those if we know the framework? (Since we are not able to figure out what ->initialize does without someone telling use we might not be that smart...)

   * @param  xyzEventDispatcher $dispatcher  An xyzEventDispatcher instance

Yeah, the type-hint is there. So if the method expects a "xyzEventDispatcher instance" we need to pass in a "xyzEventDispatcher instance". Good to know.

   * @param  array  $parameters  An associative array of initialization parameters
   * @param  array  $attributes  An associative array of initialization attributes
   * @param  array  $options     An associative array of options

Ok. So it's not a linear array. But that i need to pass "initialization parameters" to an "initialise" method i could have figured out.

Still no clue what i actually need to pass in there but as long as its documented it has to be fine!

   * @return bool true, if initialization completes successfully, otherwise false

So a boolean return value is "true" for "good" and "false" for bad".

   * @throws <b>xyzInitializationException</b> If an error occurs while initializing this xyzRequest
   */

So an exception is thrown if an error occurs while we are doing what the function is named?

So exceptions are used for error cases. Ok. Good to know.

  • Doesn't tell me the difference between return false and an exception.
  • The @throws its self is fine because it adds information
  • Btw: Why is this BOLD and not a @link

As a student in computer engineering I have been pressured to type up very detailed comments for everything I do. I can see this being very useful for group projects or in the work place but when you work on your own projects do you spend as much time commenting?

As a personal project I am working on grows more and more complicated I sometimes feel as though I should be commenting more but I also feel as though it's a waste of time since I will probably be the only one working on it. Is it worth the time and cluttered code?

Thoughts?

EDIT: This has given me a lot to think about. Thanks for all your input! I never expected this large of a response.

If the code is well written, with short methods (see Composed Method pattern) and meaningful names, then the code needs very little comments. Only comments which explain the "why" are useful - the comments explaining "what" should be replaced by improving the code so much that it's obvious what it does. Comments should not be used as an excuse for writing bad code.

Public APIs, especially in closed-source apps, are perhaps the only place where thorough javadocs are recommended - and then you need to take the effort to maintain them and keep them always accurate and up-to-date. A misleading or outdated comment is worse than no comment. It's better to document what the code does by writing tests for it and using good names for the tests.

The book Clean Code has a good chapter about comments.

In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.

In Optimizing software in C++ Agner Fog states that he does not like the rule of breaking up a function just because it crosses a certain threshold of a number of lines. He states that this results in unnecessary jumps which degrade performance.

First off, I understand that it will not matter if the code I am working on is not in a tight loop and that the functions are heavy so that the time it takes to call them is dwarfed by the time the code in the function takes to execute. But let's assume that I am working with functions that are, most of the time, used by other objects/functions and are performing relatively trivial tasks. These functions follow the suggestions listed in the first paragraph (that is, perform one single function and are small/comprehensible). Then I start programming a performance critical function that utilizes these other functions in a tight loop and is essentially a frame function. Lastly, assume that in-lining them has a benefit for the performance critical function but no benefit whatsoever to any other function (yes, I have profiled this, albeit with a lot of copying and pasting which I want to avoid).

Immediately, one can say that tag the function inline and let the compiler choose. But what if I don't want all those functions to be in a `.inl file or exposed in the header? In my current situation, the performance critical functions and the other functions it uses are all in the same source file.

To sum it up, can I selectively (force) inline a function(s) for a single function so that the end code behaves like it is one big function instead of several calls to other functions.

You cannot force the inline. Also, function calls are pretty cheap on modern CPUs, compared to the cost of the work done. If your functions are large enough to need to be broken down, the additional time taken to do the call will be essentially nothing.

Failing that, you could ... try ... to use a macro.

Robert C. Martin offers in the fist chapter of his book 'Clean Code' several definitions of 'clean code' from differen well known software experts. How do you define clean code?

  • Easy to understand.
  • Easy to modify.
  • Easy to test.
  • Works correctly (Kent Beck's suggestion - very right).

These are the things that are important to me.

If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

In Clean Code, page 124, Robert C. Martin writes:

The moral of the story is simple: Test code is just as important as production code. It is not a second-class citizen. It requires thought, design, and care. It must be kept as clean as production code.

I have recently (in the last week) embarked on an experiment wherein I attempt to code a new feature in a project I'm working on using TDD principles. In the past, our approach has been a moderately-agile approach, but with no great rigour. Unit testing happens here and there when it's convenient. The main barrier to comprehensive test coverage is that our application has a complicated web of dependencies. I picked a feature that was convenient to wall off to try my experiment on; the details aren't important and probably commercially sensitive, suffice to say that it's a simple optimisation problem.

Thus far I have found that:

  • TDD for me seems to encourage rambling, non-obvious designs to take shape. The restriction that one must not write code without a test tends to block opportunities to factor out functionality into independent units. Thnking up and writing tests for that many features simultaneously is too difficult in practice
  • TDD tends to encourage the creation of 'God Objects' that do everything - because you've written lots of mocking classes for class x already, but few for class y, so it seems logical at the time that class x should also implement feature z instead of leaving it to class y.
  • Writing tests before you write code requires that you have a complete understanding of every intricacy of the problem before you solve it. This seems like a contradiction.
  • I haven't been able to get the team on-side to start using a mocking framework. This means that there is a proliferation of cruft created solely to test a particular feature. For every method tested, you'll tend to need a fake whose only job is to report that the class under test called whatever it's supposed to. I'm starting to find myself writing something resembling a DSL purely for instantiating the test data.
  • Despite the above concerns, TDD has produced a working design with few mysterious errors, unlike the development pattern I'm used to. Refactoring the sprawling mess that results however has required that I temporarily abandon the TDD and just get it done. I'm trusting that the tests will continue to enforce correctness in the method. Trying to TDD the refactoring exercise I feel will just proliferate more cruft.

The question then, is "Does anybody have any advice to reduce the impact of the concerns listed above?". I have no doubt that a mocking framework would be advantageous; however at present I'm already pushing my luck trying something that appears to merely produce rambling code.

edit #1:

Thank you all for your considered answers. I admit that I wrote my question after a few friday-evening beers, so in places it's vague and doesn't really express the sentiments that I really intended. I'd like to emphasise that I do like the philosophy of TDD, and have found it moderately successful, but also surprising for the reasons I listed. I have the opportunity to sleep on it and look at the problem again with fresh eyes next week, so perhaps I'll be able to resolve my issues by muddling through. None of them are non-starters, however.

What concerns me more is that some of the team members are resistant to trying anything that you could call a 'technique' in favour of 'just getting it done'. I am concerned that the appearance of cruft will be taken as a black mark against the process, rather than evidence that it needs to be done completely (i.e. with a mocking framework and strong DI) for best results.

RE "TDD doesn't have to mean test-first": (womp, btreat)

The 'golden rule' in every text I've found on the issue is "Red, Green, Refactor". That is:

  • Write a test that MUST fail
  • Write code that passes the test
  • Refactor the code so that it passes the test in the neatest practical way

I am curious as to how one imagines doing Test-Driven Development without following the core principle of TDD as originally written. My colleague calls the halfway house (or a different and equally valid approach, depending on your perspective) "Test-Validated Development". In this case I think coining a new term - or possibly stealing it off somebody else and taking credit for it - is useful.

RE DSLs for test data: (Michael Venable)

I'm glad you said that. I do see the general form being increasingly useful across the scope of the project, as the application in question maintains a pretty complicated object graph and typically, testing it means running the application and trying things out in the GUI. (Not going to give the game away for commercial sensitivity reasons above, but it's fundamentally to do with optimisation of various metrics on a directed graph. However, there are lots of caveats and user-configurable widgets involved.)

Being able to set up a meaningful test case programmatically will help in all manner of situations, potentially not limited to unit testing.

RE God Objects:

I felt this way because one class seemed to be taking up most of the feature-set. Maybe this is fine, and it really is that important, but it raised a few eyebrows because it looked just like older code that wasn't developed along these lines, and appeared to violate SRP. I suppose it's inevitable that some classes will function primarily as seams between numerous different encapsulated bits of functionality and others will seam only a few. If it's going to be that way, I suppose what I need to do is purge as much of the logic as possible from this apparent God Object and recast its behaviour as a junction point between all the factored-out parts.

(to the moderators: I've added my responses to posts up here because the comment field isn't long enough to contain the detail I'd like.)

edit #2 (after about five months):

Well, I felt it might be nice to update with some more thoughts after mulling the issue over for a while.

I did end up abandoning the TDD approach in the end, I'm sorry to say. However, I feel that there are some specific and justified reasons for this, and I'm all ready to continue with it the next time I get an opportunity.

A consequence of the unapologetic refactoring mentality of TDD is that I was not greatly upset when, upon taking a brief look at my code, the lead dev declared that the vast majority of it was pointless and needed to go. While there is a twinge of regret at having to cast off a huge swathe of hard work, I saw exactly what he meant.

This situation had arisen because I took the rule of 'code to an interface' literally, but continued to write classes that tried to represent reality. Quite a long time ago I first made the statement:

Classes should not attempt to represent reality. The object model should only attempt to solve the problem at hand.

...which I have repeated as often as I can since; to myself and to anybody else who will listen.

The result of this behaviour was an object model of classes that performed a function, and a mirroring set of interfaces which repeated the functionality of the classes. Having had this pointed out to me and after a brief but intense period of resistance, saw the light and had no problem with deleting most of it.

That doesn't mean that I believe 'code to an interface' is bunk. What it does mean is that coding to an interface is primarily valuable when the interfaces represent real business functions, rather than the properties of some imagined perfect object model that looks like a miniature copy of real life, but doesn't consider its sole meaning in life to be answering the question you originally asked. The strength of TDD is that it can't produce models like this, except by chance. Since it starts with asking a question and only cares about getting an answer, your ego and prior knowledge of the system aren't involved.

I'm rambling now, so I'd do best to finish this and just state that I am all raring to go at trying TDD again, but have a better overview of the tools and tactics available and will do my best to decide how I want to go about it before jumping in. Perhaps I should transplant this waffle to a blog where it belongs, once I have something more to say about it.

To begin with, try reviewing your method against a reference book (e.g. Beck's book). When you're learning something - follow the rule without questioning. A common mistake to adapt a method prematurely without understanding the implications of your changes.
e.g. (as Carl posted) the books I've read advocate writing one unit test at a time and watching it fail before filling in the implementation.

Once it passes, you need to "refactor". Small word but big implications - its the make-or-break step. You improve your design in a flurry of little steps. However TDD is no substitute for experience... which stems from practice. So an experienced programmer with/without TDD may still end producing better code than a novice with TDD - because he/she knows what to look out for. So how do you get there ? You learn from the people who have been doing it a while.

  • I'd recommend Beck's TDD By Example book first. (Freeman and Pryce's GOOS book is good but you'd get better value from it once you've been doing TDD for a while.)
  • For tapping into the Guru's mind, check out Clean Code by Bob Martin. It gives you simple heuristics to evaluate your choices against. I'm at chapter 3 ; I've even setup a group-reading exercise @ work. As the book says, Clean code is equal measures of discipline, technique + "code-sense".

I'm running into more and more naming clashes between Android activities and other classes. I was wondering if you could tell me how you avoid these. Sadly, my particular naming problems are not covered in the related questions on SO.

First example

I have an activity that displays a level of the game. However, the data required for that level (background artwork, entities etc.) is stored in a separate class. Naturally, I would call the latter class Level. However, I would call the activity Level as well, because it displays levels.

Second example

I have an activity that plays back a cut scene. It basically displays several images in a row. The information which image is shown for how long is stored in a separate class. As in the previous case, I would naturally call both classes CutScene.

How would you solve these naming issues? Name the activities LevelActivity and CutSceneActivity? Name the representation classes LevelModel and CutSceneModel? Something else?

In general the best way to name android application components is to add its "component type" as suffix. Example :-

  • LevelActivity (LevelActivity extends Activity)
  • InboxUpdateService (InboxUpdateService extends Service)
  • ContactsContentProvider (ContactsContentProvide extends ContentProvider)
  • SMSBroadcastReceiver (SMSBroadcastReceiver extends BroadcastReceiver)

By naming using above method there will be minimal chances of losing track when you're working on big code flow with lots of similar names in your application.

So, name your Activities with suffix "Activity".

And name the Class which provides Data to your LevelActivity as Level.

In Contradiction to second part of Pascal MARTIN's answer, you can also use LevelActivity and LevelInfo together. Because they offer clear difference as quoted below:

Distinguish names in such a way that the reader knows what the differences offer - Robert. C. Martin, author of Clean Code

But the suffix are often redundant on cognitive basis. Using only the word Level clearly emphasises that class Level offers information about Level. So, use Level for class that provides data about Level.

NOTE : If you're using suffixes, choose one word per concept. For Example: If you're using the suffix Info to identify classes that offer information then only Info should be used (not Data or Model) throughout your application to avoid confusions.

I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been addressed elsewhere), but I'm also interested in understanding how documentation and unit testing go together.

How can unit tests be documented to improve their utility when those tests fail in the future? Specifically, what makes a good unit test docstring?

I'd appreciate both descriptive answers and examples of unit tests with excellent documentation. Though I'm working exclusively with Python, I'm open to practices from other languages.

Perhaps the issue isn't in how best to write test docstrings, but how to write the tests themselves? Refactoring tests in such a way that they're self documenting can go a long way, and your docstring won't go stale when the code changes.

There's a few things you can do to make the tests clearer:

  • clear & descriptive test method names (already mentioned)
  • test body should be clear and concise (self documenting)
  • abstract away complicated setup/teardown etc. in methods
  • more?

For example, if you have a test like this:

def test_widget_run_returns_0():
    widget = Widget(param1, param2, "another param")
    widget.set_option(true)
    widget.set_temp_dir("/tmp/widget_tmp")
    widget.destination_ip = "10.10.10.99"

    return_value = widget.run()

    assert return_value == 0
    assert widget.response == "My expected response"
    assert widget.errors == None

You might replace the setup statements with a method call:

def test_widget_run_returns_0():
    widget = create_basic_widget()
    return_value = widget.run()
    assert return_value == 0
    assert_basic_widget(widget)

def create_basic_widget():
    widget = Widget(param1, param2, "another param")
    widget.set_option(true)
    widget.set_temp_dir("/tmp/widget_tmp")
    widget.destination_ip = "10.10.10.99"
    return widget

def assert_basic_widget():
    assert widget.response == "My expected response"
    assert widget.errors == None

Note that your test method is now composed of a series of method calls with intent-revealing names, a sort of DSL specific to your tests. Does a test like that still need documentation?

Another thing to note is that your test method is mainly at one level of abstraction. Someone reading the test method will see the algorithm is:

  • creating a widget
  • calling run on the widget
  • asserting the code did what we expect

Their understanding of the test method is not muddied by the details of setting up the widget, which is one level of abstraction lower than the test method.

The first version of the test method follows the Inline Setup pattern. The second version follows Creation Method and Delegated Setup patterns.

Generally I'm against comments, except where they explain the "why" of the code. Reading Uncle Bob Martin's Clean Code convinced me of this. There is a chapter on comments, and there is a chapter on testing. I recommend it.

For more on automated testing best practices, do check out xUnit Patterns.

(Sorry, I'm stupid and uneducated, so this is probably a ridiculous question.)

I just started looking at J, and they use the terms "monadic" and "dyadic" for what seems (to me) to be unary and binary operators. Why is this done, and how does it relate to the other place I've heard the term (Haskell)? My guess is they are unrelated homonyms but I'm not sure.

No, the J use has nothing to do with the Haskell term. Monadic and dyadic functions are functions of one and two arguments, respectively.

The J terms originate from APL, which is a bit older than Haskell, but I have rarely seen them used like this outside of the APL family.

One example of the use of these terms in a non-APL context is from the book Clean Code, which in the chapter about functions talks about niladic, monadic and dyadic functions.

In object oriented programming, a custom class (like Person class with data of Name, list of addresses, etc)holds data and can include collection objects too. A data structure is also used to hold data too. So, is a class considered advanced data structure conceptually ? And in design of efficient systems (in object oriented world and large systems), are classes considered as similar to data structures and algorithmic analysis done for efficient classes designs for greater efficiency(in companies like google, facebook) ?

I recommend you to read Clean Code chapter 6: objects and data structures. The whole chapter is about this... You can read an abstract if you don't want to buy the book, it can be found here.

According to that, you can use classes efficiently in two different ways. This phenomenon is called data/object anti-symmetry. Depending on your goals, you have to decide whether your classes will follow the open/closed principle or not.
If they follow the OCP, they will be polymorph, and their instances will be used as objects. So they will hide data and implementation of a common interface, and it will be easy to add a new type which implements that interface as well. Most of the design patterns fulfill the OCP, for example MVC, IoC, every wrapper, adapter, etc...
If they don't follow the OCP, they won't be polymorph, their instances will be used as data structures. So they will expose data, and that data will be manipulated by other classes. This is a typical approach by procedural programming as well. There are several examples which don't use OCP, for example DTOs, Exceptions, config objects, visitor pattern etc...

Typical pattern when you should think about fulfilling OCP and move the code to a lower abstraction level:

class Manipulator {
    doSomething(Object dataStructure){
        if (dataStructure instanceof MyType1){
            // doSomething implementation 1
        }
        else if (dataStructure instanceof MyType2)
        {
            // doSomething implementation 2
        }
        // ...
    },
    domSomethingElse(Object dataStructure){
        if (dataStructure instanceof MyType1){
            // domSomethingElse implementation 1
        }
        else if (dataStructure instanceof MyType2)
        {
            // domSomethingElse implementation 2
        }
        // ...
    }
}

class MyType1 {}
class MyType2 {}
//if you want to add a new type, every method of the Manipulator will change

fix: moving implementation to a lower abstraction level and fulfill OCP

interface MyType {
    doSomething();
    domSomethingElse();
}

class MyType1 implements MyType {
    doSomething(){
        // doSomething implementation 1
    },
    domSomethingElse(){
        // domSomethingElse implementation 1
    }
}

class MyType2 implements MyType {
    doSomething(){
        // doSomething implementation 2
    },
    domSomethingElse(){
        // domSomethingElse implementation 2
    }
}

// the recently added new type
class MyType3 implements MyType {
    doSomething(){
        // doSomething implementation 3
    },
    domSomethingElse(){
        // domSomethingElse implementation 3
    }
}

Typical pattern when you should think about violating OCP and move the code to an higher abstraction level:

interface MyType {
    doSomething();
    domSomethingElse();

    //if you want to add a new method here, every class which implements this interface, will be modified
}

class MyType1 implements MyType {
    doSomething(){
        // doSomething implementation 1
    },
    domSomethingElse(){
        // domSomethingElse implementation 1
    }
}

class MyType2 implements MyType {
    doSomething(){
        // doSomething implementation 2
    },
    domSomethingElse(){
        // domSomethingElse implementation 2
    }
}

or

interface MyType {
    doSomething();
    domSomethingElse();
}

class MyType1 implements MyType {
    doSomething(){
        // doSomething implementation 1
    },
    domSomethingElse(){
        // domSomethingElse implementation 1
    }
}

class MyType2 implements MyType {
    doSomething(){
        // doSomething implementation 2
    },
    domSomethingElse(){
        // domSomethingElse implementation 2
    }
}

//adding a new type by which one or more of the methods are meaningless
class MyType3 implements MyType {
    doSomething(){
        throw new Exception("Not implemented, because it does not make any sense.");
    },
    domSomethingElse(){
        // domSomethingElse implementation 3
    }
}

fix: moving implementation to a higher abstraction level and violate OCP

class Manipulator {
    doSomething(Object dataStructure){
        if (dataStructure instanceof MyType1){
            // doSomething implementation 1
        }
        else if (dataStructure instanceof MyType2)
        {
            // doSomething implementation 2
        }
        // ...
    },
    domSomethingElse(Object dataStructure){
        if (dataStructure instanceof MyType1){
            // domSomethingElse implementation 1
        }
        else if (dataStructure instanceof MyType2)
        {
            // domSomethingElse implementation 2
        }
        // ...
    },
    // the recently added new method
    doAnotherThing(Object dataStructure){
        if (dataStructure instanceof MyType1){
            // doAnotherThing implementation 1
        }
        else if (dataStructure instanceof MyType2)
        {
            // doAnotherThing implementation 2
        }
        // ...
    }
}

class MyType1 {}
class MyType2 {}

or splitting up the classes into subclasses.

People usually follow OCP over the method count one or two because repeating the same if-else statements is not DRY enough.

I don't recommend you to use mixed classes which partially fulfill, partially violate the OCP, because then the code will be very hard maintainable. You should decide by every situation which approach you follow. This should be usually an easy decision, but if you make a mistake, you can still refactor your code later...

A typical call to performSelectorOnMainThread: looks like this:

[target performSelectorOnMainThread:action withObject:foo waitUntilDone:NO];

where "result" is an argument passed to "action". A corresponding action would be:

- (void)doSomethingWithThing1:(id *)thing1

What is the correct syntax for calling an action that takes > 1 argument? Such as:

- (void)doSomethingWithThing1:(id *)thing1 andThing2(id *)thing2 andAlsoThing3(id *)thing3

[target performSelectorOnMainThread:action withObject:??? waitUntilDone:NO];

If you wish to preserve the method signature of the receiver then I think you'll need to look at using NSInvocation which allows you to specify multiple argument values.

You could wrap your call and use a dictionary as a container for your arguments as suggested in another answer but to me this seems like a bit of a code smell.

A better solution along this line would be to create a class that encapsulates the argument values - i.e. a strongly typed approach. So for example instead of passing firstname, surname, you'd pass an instance of a Person class. This is probably a better route to go down because methods with fewer arguments can yield cleaner code - but that's a whole other story.

I am in the middle of reading the excellent Clean Code

One discussion is regarding passing nulls into a method.

public class MetricsCalculator {
    public double xProjection(Point p1, Point p2) {
        return (p2.x - p1.x) * 1.5;
    }
}
...
calculator.xProjection(null, new Point(12,13));

It represents different ways of handling this:

public double xProjection(Point p1, Point p2) {
    if (p1 == null || p2 == null) {
        throw new IllegalArgumentException("Invalid argument for xProjection");
    }
    return (p2.x - p1.x) * 1.5;
}

public double xProjection(Point p1, Point p2) {
    assert p1 != null : "p1 should not be null";
    assert p2 != null : "p2 should not be null";
    return (p2.x - p1.x) * 1.5;
}

I prefer the assertions approach, but I don't like the fact that assertions are turned off by default.

The book finally states:

In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.

It doesn't really go into how you would enforce this restriction?

Do any of you have strong opinions either way.

Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here.

  • Assertions have the advantage of performance as they are typically disabled on production systems.
  • Exceptions have the advantage of safety, as the check is always performed.

The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion.

Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException.

Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.

I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning programmer? I don't think I'd have as many problems if I knew a little about the thought processes that go into software design.

Check out this book: Head First Design Patterns ...literally. Check it out. From the library.

Head First Design Patterns would be a good place to start for a beginner. It's probably easier to get into than the Gang of four book.

I would definitely add another book. I think that Clean Code by Bob Martin is a very good book to tell you how to write code that is maintainable. It introduces several easy rules that leads to code that is very well structured and readable.

Sounds like you want a book on design patterns.

Take a look at: Design Patterns - Elements of Reusable Object-Oriented Software. Warning it is not Python specific though.

You could also take at this online resource for Python design patterns.

Stackoverflow user @S.Lott also has a lot of really good Python resources that he wrote. You can see them on his Stackoverflow page.

I was in the shower and thought about something.

The deferred / promise pattern is to decrease callback hell, by allowing the developer to chain call functions, as mentioned here:

Parse.User.logIn("user", "pass").then(function(user) {
  return query.find();
}).then(function(results) {
  return results[0].save({ key: value });
}).then(function(result) {
  // the object was saved.
});

From the top of my head - correct me if I am wrong - but it seems like using deferred / promises is an easy way to break the Law of Demeter?

The Law of Demeter states:

A method of an object may only call methods of:

  • The object itself.
  • An argument of the method.
  • Any object created within the method.
  • Any direct properties/fields of the object.

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

Any comments concerning this?

Update December 1 2013:

A summarized version of my question. The Promise framework is designed to simplify asynchronous coding and avoid "callback hell". One of the most beneficial features of Promise is that you can chain-call events by using .then(), as seen in my example above.

Given all code/functions are now using Promise (like Benjamin Gruenbaum (author below) is currently doing), won't it open it up to make chain-calling functions really easy by going .then().then().then() etc.

Writing code that chain-call functions after each other (.then().then().then()) has to be a text-book example of how to break the Law of Demeter.

Hence my question; Does the Promise framework promote / open up / make it easier to abuse / break the Law of Demeter?

The short answer is Yes.

I think this has been made more complicated than necessary because people have confused the issue with points that while interesting aren't directly relevant to the Law of Demeter. Like the fact we are talking JavaScript. Or the fact we are dealing in callbacks. Those are details that just don't apply.

Let's step back and reset the discussion. The overarching goal in software engineering is to limit coupling as much as possible. In other words, when I change code, I want to make sure that doesn't force me to work on the weekend to change a ton of other code as a consequence. The Law of Demeter exists to prevent one type of coupling--feature envy. It does so by providing formal limits to what a method f can use to do its job.

The OP @corgrath was nice enough to enumerate these limits. An easy way to characterize a violation of the Law of Demeter is this: "You can't call any methods on any of the 4 objects allowed."

Now finally to the sample code provided by @corgrath:

Parse.User.logIn("user", "pass").then(function(user) {
  return query.find();
}).then(function(results) {
  return results[0].save({ key: value });
}).then(function(result) {
  // the object was saved.
});

Let's call Parse a data structure as opposed to an object (See Chapter 6 of Uncle Bob's fabulous book Clean Code, which was my first exposure to the Law of Demeter, for more on the distinction). Then we are fine with Parse.User.

But User is clearly an object with methods and behavior. One of these methods is logIn. This returns a Promise. As soon as we call anything on this object, we have violated the Law of Demeter.

That's it.

As an aside, I will mention quickly also that in JavaScript functions are objects. So the Law of Demeter would also apply to the callback functions passed to each then call. But within each none of the function's methods, which do exist, are called, so the then calls do not violate the Law of Demeter.

Now what's interesting is whether this clear violation of the Law of Demeter matters. Software engineering is an art. We have all kinds of laws and principles and practices, but religious adherence to them is just as counterproductive as ignorance of them. It is stupid to attempt 100% code coverage; it is stupid to unit test getters and setters; it is stupid to fight for 100% class cohesion; it is stupid to create 100% package stability; etc.

In this case, I would say the violation of the Law of Demeter doesn't matter. Promises don't expose internals in any way; they expose an abstraction for performing another action (in this case, registering a callback, but that is irrelevant to the discussion). Put another way, do I have to worry about working on the weekend by making all these then calls? The likelihood is realllly low. I mean it's possible they will rename the method to andThen or whenYoureReadyDoThis, but I doubt it.

This is a big deal because I like my weekends. I don't want to work on unnecessary things. I want to do fun stuff like posting essay answers on Stack Overflow.

So in summary, there are two questions:

  • Does the Promise code break the Law of Demeter? Yes.
  • Does it matter? No

Conflating the two and bringing all kinds of extraneous information into the discussion only confuses the matter.

Can any one suggest what is the best way to write good code that is understandable without a single line of comments?

Read Code Complete, 2nd Edition cover to cover. Perhaps twice.

To give some specifics:

  • Making code readable
  • Eliminating code repetition
  • Doing design/architecture before you write code

Clean Code by Robert C. Martin contains everything you need to write clean, understandable code.

I've been reading the book Clean Code: A Handbook of Agile Software Craftsmanship and in one chapter it mentions the following

  • Objects hide their data behind abstractions and expose functions that operate on that data. Data structures expose their data and have no meaningful functions.

  • Object expose behavior and hide data. This makes it easy to add new kinds of objects without changing existing behaviors. It also makes it hard to add new behaviors to existing objects.

  • Data structures expose data and have no significant behavior. This makes it easy to add new behaviors to existing data structures but makes it hard to add new data structures to existing functions.

I'm a tad bit confused whether some classes are objects or data structures. Say for example HashMaps in java.util, are they objects? (because of its methods like put(), get(), we dont know their inner workings) or are they data structures? (I've always thought of it as data structures because its a Map).

Strings as well, are they data structures or objects?

So far majority of the code I've been writing have been the so called "hybrid classes" which try to act as an object and a data structure as well. Any tips on how to avoid them as well?

An object is an instance of a class. A class can model various things from the real world. It's an abstraction of something (car, socket, map, connection, student, teacher, you name it).

A data structure is a structure which organizes certain data in a certain way. You can implement structures in ways different that by using classes (that's what you do in languages which don't support OOP e.g.; you can still implement a data structure in C let's say).

HashMap in java is a class which models a map data structure using hash-based implementation, that's why it's called HashMap.

Socket in java is a class which doesn't model a data structure but something else (a socket).

So,

I have been working on re-factoring some legacy code recently and have found myself questioning the validity of some of the re-factoring decisions I have been making. One such query has been about the use of instance variables for object sharing between methods within an object.

Specifically, there are a number of places where constructors & methods have been split up and local variables promoted to instance variables, allowing access from the now separate methods. This, to me, seems wrong. It breaks encapsulation, alters scope and can affect life cycle, however, some of these classes are performance related and thus I wonder what the implication of re-factoring these methods to use parameter passing instead may be?

More to the point I wonder whether my assumptions even hold water? Is parameter passing of objects preferable to instance variables when it comes to sharing between private methods?

On the plus site this way you wont have to pass those arguments to other methods. When a method has more than three arguments (according to Robert Martin's Clean Code) readability of your code starts to decrease fast. I think you should mix these two methods to bet the best result.

What you could do is look if you can extract a new class from part of the existing one. When just part of the methods use these instance fields, perhaps those methods are doing something that can be abstracted. This way you can create a new class with the instance fields as constructor arguments or properties and instantiate it.

how i can improve our code quality and write clean code. if i write a unclean ugly code then how i can migrate as a good code (beautiful and clean).

Read Robert Martin's Clean Code: A Handbook of Agile Software Craftsmanship

Yes, I know 'Java', but it really is a very good book.

I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here?

First rule of threading: don't thread. Second rule of threading: if you have to violate rule one...don't. Third rule: OK, fine you have to use threads, so before proceeding get your head into the pitfalls, understand locking and the common thread problems such as deadlock and livelocking.

Understand that threading does not speed up anything, it is only useful to background long-running processes allowing the user can do something else with the application. If you have to allow the user to interact with the application while the app does something else in the background, like poll a socket or wait for ansynchronous input from elsewhere in the application, then you may indeed require threading.

The thread sections in both Effective Java and Clean Code are good introductions to threads and their pitfalls.

I'm currently developing a graphical analysis package for R. We're trying to use principles from both Clean Code and Test-Driven Development (TDD). But, we've run into a conceptual problem.

How can you test unexposed functions?

Consider the following simplified example. Outer() is a function we're building in our package, and we expose it to users by listing it in the NAMESPACE file. Inner() is a short (~5 line) utility function:

Outer <- function(...) {

  Inner <- function(...) {
    return(x)
  }

  return( Inner() )
}

Most of the user-exposed functions in our package are collections of short, single-behavior Inner() style functions that lie under the umbrella of a single Outer() function the user can call. Granova.ds.ggplot() is one example. Such a modular design is strongly advocated by Clean Code, and we're quite happy with the results. But we don't know how to build unit tests for it, since the functions we want to test aren't accessible outside the scope of the Granova.ds.ggplot() function given how we designed it.

Several ideas/solutions occurred to us:

  1. Tests should only have access to public APIs. Since functions like Inner() are by design not public (they're not exported in NAMESPACE) we shouldn't even be trying to test them.
  2. Hadley Wickham's testthat package wiki says it supports testing of "non-exported functions" using an R CMD check workflow.
  3. If all else fails, we could somehow manually break our Outer() functions for testing purposes

None of these solutions has worked so far

Solution 1 seems like a cop-out. We believe that especially in R, it's sensible to have a top-level function that calls various short, single-responsibility utility methods. Not being able to test such methods seems silly, and like the type of thing there's a solution for but we just haven't found yet.

Solution 2 might work, but we haven't gotten it to work so far. If you try cloning our repository, then sourcing inst/dev.R I believe you'll find in the test output that it cannot find the function InitializeGgplot(), even though said function is defined in lines 613-615 of granova.1w.ggplot(). Similarly, running R CMD check at the terminal doesn't seem to execute any of our tests at all. It does take a great deal of time and throw insulting errors at us, though :-(

Solution 3 is in a sense pragmatic, but counter to the aim of always moving toward a goal state of the project. It doesn't make sense to us.

What would be the ideal solution

Ideally, we're looking for a way to leverage a package like testthat to rapidly provide feedback as we code, and to allow us to test functions like Inner() that exist within functions like Outer(). Even better would be a way to do it without resorting to R CMD check, which due to the 3-d complexity of some of our functions takes almost a full minute to run each time.

So, what are we missing? Should TDD practices allow for testing Outer/Inner style setups in R? If they do, how can we do so in developing our package? Any feedback is welcome, and I'll try to respond to anything that's unclear.

Thanks!

If Inner implements non-trivial functionality that you want to test, I'd suggest moving Inner to the top-level, but not exporting it. Generally, I avoid nesting functions within other functions for exactly this reason - they're hard to test.

You can test during development with the usual testthat functions because you're probably just sourcing in all your R code and not worrying about namespaces (at least that's how I develop). You then use R CMD check in conjunction with test_package to ensure the tests still work at build time - test_packages runs the tests in the package namespace so they can test non-exported functions.

I'm running a refactoring code dojo for some coworkers who asked how refactoring and patterns go together, and I need a sample code base. Anyone know of a good starting point that isn't to horrible they can't make heads or tails of the code, but can rewrite their way to something useful?

I'm searching for the best pattern to implement client/server socket communication using appropriate features of Java 1.7 (try-with-resources). It must be assured all threads and resources are closed and released completely. Effective Java/Clean Code items should be considered as well as simple debugability (only one statement in each line).

Any feedback or discussion would be appreciated.

First approach

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

public final class ThreadedServerTest1 {
    private static final class ThreadedServer implements Runnable {
        private final Socket socket;

        ThreadedServer(final Socket socket) {
            this.socket = socket;
        }

        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            try (final ServerSocket serverSocket = new ServerSocket(port)) {
                while (true) {
                    final Socket socket = serverSocket.accept();
                    final ThreadedServer server = new ThreadedServer(socket);
                    final Thread thread = new Thread(server);
                    thread.start();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            // @formatter:off
            try (
                // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7027552 and
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7013420:
                final Socket socket = this.socket;
                final InputStream inputStream = socket.getInputStream();
                final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                final OutputStream outputStream = socket.getOutputStream();
                final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                final PrintWriter printWriter = new PrintWriter(outputStreamWriter);
            ) {
                // @formatter:on
                final String request = bufferedReader.readLine();
                System.out.println(String.format("Received from client: %s", request));
                printWriter.println("Hello client!");
                printWriter.flush();
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static final class Client {
        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            try {
                final InetAddress loopbackAddress = InetAddress.getByName(null);
                // @formatter:off
                try (
                    final Socket socket = new Socket(loopbackAddress, port);
                    final OutputStream outputStream = socket.getOutputStream();
                    final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                    final PrintWriter printWriter = new PrintWriter(outputStreamWriter);
                    final InputStream inputStream = socket.getInputStream();
                    final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
                ) {
                    // @formatter:on
                    printWriter.println("Hello server!");
                    printWriter.flush();
                    final String answer = bufferedReader.readLine();
                    System.out.println(String.format("Answer from server: %s", answer));
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            } catch (final UnknownHostException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test() {
        final String[] arguments = new String[] { "9999" };
        final Thread tread = new Thread() {
            @Override
            public void run() {
                ThreadedServer.main(arguments);
            };
        };
        tread.start();
        Client.main(arguments);
    }
}

Pros:

  • Less lines of code

Cons:

  • Large try-with-resources blocks (no support in Eclipse formatter)
  • Second Socket instance needed to use try-with-resources
  • Deep nesting because of the UnknownHostException from InetAddress#getByName(null)

Second approach

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

public final class ThreadedServerTest2 {
    private static final class Connection implements AutoCloseable {
        final Socket socket;
        final InputStream inputStream;
        final InputStreamReader inputStreamReader;
        final BufferedReader bufferedReader;
        final OutputStream outputStream;
        final OutputStreamWriter outputStreamWriter;
        final PrintWriter printWriter;

        private Connection(final Socket socket) throws IOException {
            this.socket = socket;
            inputStream = socket.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            outputStream = socket.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            printWriter = new PrintWriter(outputStreamWriter);
        }

        static Connection serverConnection(final Socket socket) throws IOException {
            return new Connection(socket);
        }

        static Connection clientConnection(final String hostname, final int port) throws IOException {
            final InetAddress inetAddress = InetAddress.getByName(hostname);
            final Socket socket = new Socket(inetAddress, port);
            return new Connection(socket);
        }

        static Connection localhostCientConnection(final int port) throws IOException {
            return clientConnection(null, port);
        }

        @Override
        public void close() {
            closeAndIgnoreException(printWriter, outputStreamWriter, outputStream, bufferedReader, inputStreamReader, inputStream, socket);
        }

        private void closeAndIgnoreException(final AutoCloseable... closeables) {
            for (final AutoCloseable closeable : closeables) {
                try {
                    closeable.close();
                } catch (final Exception ignore) {
                }
            }
        }
    }

    private static final class ThreadedServer implements Runnable {
        private final Socket socket;

        private ThreadedServer(final Socket socket) {
            this.socket = socket;
        }

        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            try (final ServerSocket serverSocket = new ServerSocket(port)) {
                while (true) {
                    final Socket socket = serverSocket.accept();
                    final ThreadedServer server = new ThreadedServer(socket);
                    final Thread thread = new Thread(server);
                    thread.start();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try (Connection connection = Connection.serverConnection(socket)) {
                final String request = connection.bufferedReader.readLine();
                System.out.println(String.format("Received from client: %s", request));
                connection.printWriter.println("Hello client!");
                connection.printWriter.flush();
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static final class Client {
        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            try (Connection connection = Connection.localhostCientConnection(port)) {
                connection.printWriter.println("Hello server!");
                connection.printWriter.flush();
                final String answer = connection.bufferedReader.readLine();
                System.out.println(String.format("Answer from server: %s", answer));
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test() {
        final String[] arguments = new String[] { "9999" };
        final Thread tread = new Thread() {
            @Override
            public void run() {
                ThreadedServer.main(arguments);
            };
        };
        tread.start();
        Client.main(arguments);
    }
}

Pros:

  • Clean and readable try-with-resources blocks
  • Support in Eclipse formatter

Cons:

  • More lines of code
  • Own Connection class needed
  • Closing the AutoCloseable instances in the Connection class may be forgotten (error prone)

Do you have feedback or additions to the pros and cons? Are there more weaknesses?

Third approach

That's the result of the discussion below:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

public final class ThreadedServerTest3 {
    private static final class ThreadedServer implements Runnable {
        private final Socket socket;

        private ThreadedServer(final Socket socket) {
            this.socket = socket;
        }

        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            try (final ServerSocket serverSocket = new ServerSocket(port)) {
                while (true) {
                    final Socket socket = serverSocket.accept();
                    final ThreadedServer server = new ThreadedServer(socket);
                    final Thread thread = new Thread(server);
                    thread.start();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            // @formatter:off
            try (
                // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7027552 and
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7013420:
                Socket socket = this.socket;
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            ) {
                // @formatter:on
                final String request = bufferedReader.readLine();
                System.out.println(String.format("Received from client: %s", request));
                printWriter.println("Hello client!");
                printWriter.flush();
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static final class Client {
        public static void main(final String arguments[]) {
            final int port = arguments.length > 0 ? Integer.parseInt(arguments[0]) : 9999;
            // @formatter:off
            try (
                Socket socket = new Socket(InetAddress.getByName(null), port);
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ) {
                // @formatter:on
                printWriter.println("Hello server!");
                printWriter.flush();
                final String answer = bufferedReader.readLine();
                System.out.println(String.format("Answer from server: %s", answer));
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test() {
        final String[] arguments = new String[] { "9999" };
        final Thread tread = new Thread() {
            @Override
            public void run() {
                ThreadedServer.main(arguments);
            };
        };
        tread.start();
        Client.main(arguments);
    }
}

Pros:

  • Less lines of code
  • No to complex and mostly readable try-with-resources blocks
  • No ingored exceptions

Cons:

  • No support in Eclipse formatter
  • Some violations of the rule "only one statements in each line" (simple debugability)

This is probably a broad question, not quite SO style, but I'd still like to get some hints or guidelines if possible.

I've been looking through some legacy code and found a part of it that has methods with exceptions nested 3 or 4 levels down.
Is this considered to be a normal practice or should one avoid such codestyle where possible? If it should be avoided, what are the negative effects besides the increasing costs of exception handling and decreasing readability? Are there common ways of refactoring the code to avoid this?

About handling legacy code I would recommend you have a look at the book covering the topic: http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052 You dont even have to go through the whole book, just look at the things that concern you at the moment.

Also a good book regarding good practices is: http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1356340809&sr=1-1&keywords=clean+code

The best approach when handling nested exceptions is refactoring the code and using runtime instead of checked exceptions, and handling those where needed. This way the code is more readable and easier to maintain.

I am reading the book Clean Code http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

The author mentions that you should avoid words like Manager, Processor, Data or Info in the name of the class. I have used these everywhere. What are some better names? I have a class that is responsible for starting and stopping connections. So I named it ConnectionManager.

I came across a few articles like this one, which suggest that some words should never be used as part of a class name. When a class has one of those words in the name, it means the code should be refactored or redesigned.

Example:

Manager

Reason: Since almost all classes "manage" something and the meaning of "Manager" is very broad, people can put a lot of responsibilities to a "Manager" class while still being able to claim the class does "only one thing". As a result, naming a class with "Manager" does not say much about what the class actually does. The article mentioned earlier, "Naming Java Classes Without a 'Manager' ", showed this point:

For instance, take a class named "UrlManager" - you cannot tell whether it pool URLs, manipulates URLs or audits the use of them. All the name tells you is that this is not a URL, but it does somehow work with them. On the other hand, the name "UrlBuilder" gives a much better picture of what the class does.

Another example:

Helper

Reason: A class name like "ThreadHelper" makes people wonder why it's needed and why it cannot just be part of the "Thread" class. Is it actually an adapter or a decorator? If so, name it that way. Is class "Thread" taking too much responsibility already? If so, refactor and give the new class a meaningful name. "Helper" says nothing about what it's doing or how it's helping.

What are other words in a class name that would signal a need for refactoring or redesign and should be avoided? Why?

Edit: I would think those words are used a lot since

  • they generally have broad meanings
  • they can fit in almost all contexts
  • they stop designers thinking about better designs or names
  • people believe it's OK to use them

The book Clean Code listed more but no reasons were given:

Avoid words like Manager, Processor, Data, or Info in the name of a class.

It would be great if someone could provide possible reasons for them.

Related questions:

What’s the best approach to naming classes?

Utils. Check this Chris Missal's blog entry for why.

I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

I'd (also) recommend:

  • Effective C++, Effective STL by Steve Myers. They are easy to digest, yet very valuable - sometimes even illuminating.
  • Code Complete (The 1993 edition is available cheaply and not that much different). It's lengthy, but it walks across the entire field from what it means to be a programmer to how a for loop should look. (It would be better if it was shorter - the way it is it covers so much ground it's hard to place it). I hold it dear because it illustrate two points very well:
    • code is compromise
    • There are know facts, (but we still manage to get by by gut feel)
  • C++ FAQ Lite / C++ FAQ.
  • I'd throw in Facts and Fallacies by Robert Glass - it doesn't fit your request very well, but go read it.

It's natural that you are unhappy with other people's code. That's typical for programming - heck, even my own code of five years ago was written by a total n00b. That might be more articulated for C++, since it caters for different styles, and often puts freedom ("you can") over guildelines ("that's the way").

Still, mulling over existing code - yours or others - and considering how it can be improved. Also, figuring out why it is the way it is sometimes helps.


(I remember a few TheDailyWTF's where everyone would chime in how stupid and unreasonable this is - yet somewhere, buried among the me too's, was someone with domain experience explaining convincingly under what circumstances this was better than the obvious solution).

You might wnat to check out The Definitive C++ Book Guide and List

For your purposes I would especially recommend:

They are not in particular order, also you might want to read and code something in between them.

(Note: As noted by @John Dibling the Boost book might be a bit out of date, I do not have experience with that one myself)

Possible Duplicate:
Is it possible to write good and understandable code without any comments?

When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:

Java Mootools Ruby Erlang

Any tips would be appreciated? Thanks

Recommended reading: Clean Code by Robert C. Martin.

In brief, you should

  • use meaningful variable/method/class names,
  • keep your functions/methods short,
  • have each class and method do only one thing,
  • have the code in each method be on the same level of abstraction.

Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this

if (i >= 0 && (v.size() < u || d == e)) ...

or

if (foundNewLocalMaximum()) ...

(Don't try to find any meaning in the first code snippet, I just made it up :-)

Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.

The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.

Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.

Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).

How much percent of time do you spend on documentation per day as software developer and ideally how much time should given to documentation ?

Very little of my time is spent documenting code and most days the "percentage of time" is zero.

This is kind of an "old school" question. Time and experience have proven that code documentation is not the best use of your resources. Instead, the code should be written to be readable from the start - it should be self-documenting. Documentation, used sparingly, can be applied in just those places where the underlying logic cannot be made clear enough via the code itself.

If you want to learn more about the roots of this idea - and how to create self-documenting code - then the reference work is Robert C. Martin's "Clean Code". For a deeper analysis of the art as a whole (but less focus on coding standards and documentation) I'd also strongly suggest that you get the "Bible": McConnell's Code Complete 2.

Update: Here is an example of what I am talking about. Let's say that you want to have a client verify their demographic information (name, birthdate, gender, email) in a web app.

Old school developers might create a page "Verify.aspx" where the Page_Load pulls initial client demographics from the database and places the field data in UI controls. In the submit response, they might apply some business logic ("Ensure that a newly entered EMail doesn't conflict with another record's email", "check that firstname is not empty", etc.) and then populate database parameters, fill a SqlCommand object with a SQL insert statement and execute it. Yuck...but definitely how most code I've seen operates. You're likely to be tempted to explain each of these steps so people know when you've switched from DB logic to Business Logic to UI logic, etc. (e.g. "The session must have a CustomerID set").

Now, if your code is properly segmented - into database, business logic and UI layers - and you have named things in a clear and obvious way then you'll find the code itself to be easy to read. Here is (pseudocode) for how I handle this task in one of my projects:

protected void PageLoad()
{
  using (var customerLogic = new CustomerLogic(sessionData))
  {
     Customer customer = customerLogic.Fill();
     if (customer.Status == fcError.mbInvalidCustomerID) 
       throw new Exception("Invalid customer ID in validation request...");
     CopyCustomerDataToUIFields(customer);   
   }
}

protected void SubmitHandler()
{
  var customer = new Customer();
  if (!CopyUIFieldsToCustomerDataObject(customer)) return;
  using (var customerLogic = new CustomerLogic(sessionData))
  {
     customerLogic.Save(customer);
     if (customer.Status == fcError.mdDuplicateEmail)
     { 
       ErrorMessage.Text = "This email is already in use by the client having an ID of " + customer.SigninID;
       return;
      }
   }
   Response.Redirect("Home.aspx");
}

protected bool CopyUIFieldsToCustomerDataObject(Customer customer)
{
...
}

protected void CopyCustomerDataToUIFields(Customer customer)
{
...
}

Truly, what is there to document? Are you really going to put in a comment like this:

 // Copy all of the customer data in the customer object to the UI fields
 CopyCustomerDataToUIFields(customer);   

No! Because your naming conventions are well thought out and your code is all at the same level of abstraction, the documentation is completely redundant.

If the next developer wants to know more about the Business Logic, they'll open up the CustomerLogic class - which is an entirely separate and self-contained world. This kind of segmentation lets the developer work at a level of abstraction wherein the logic of their task is obvious. In the end, the need for documentation falls dramatically if you follow descriptive naming conventions and avoid mixing code that implements multiple levels of abstraction.

One last thing: segmentation also facilitates unit testing as well. This code is an almost straight paraphrase of code in a project I am working on now so this isn't just theory.

I always wondered: Are there any hard facts which would indicate that either shorter or longer identifiers are better?

Example:

clrscr()

opposed to

ClearScreen()

Short identifiers should be faster to read because there are fewer characters but longer identifiers often better resemble natural language and therefore also should be faster to read.

Are there other aspects which suggest either a short or a verbose style?

EDIT: Just to clarify: I didn't ask: "What would you do in this case?". I asked for reasons to prefer one over the other, i.e. this is not a poll question.

Please, if you can, add some reason on why one would prefer one style over the other.

Personally I like to try a follow the wisdom of Clean Code by Uncle Bob.

To me it suggests that Code should read like prose. By using descriptive names and ensuring that methods have a single responsibility we can write code that accurately describes the programmers intent obviating the need for comments (in most cases).

He goes on to make the observation that when we write code, we often spend 90% of the time reading the surrounding code and dependent code. Therefore by writing code that is inherently readable we can be far more productive in our writing of code.

Please go directly to the relevant chapter of Steve McConnell's "Code Complete" (sanitised Amazon link).

Specifically, chapter 11, "The Power of Variable Names".

So I've read the official JUnit docs, which contain a plethora of examples, but (as with many things) I have Eclipse fired up and I am writing my first JUnit test, and I'm choking on some basic design/conceptual issues.

So if my WidgetUnitTest is testing a target called Widget, I assume I'll need to create a fair number of Widgets to use throughout the test methods. Should I be constructing these Widgets in the WidgetUnitTest constructor, or in the setUp() method? Should there be a 1:1 ratio of Widgets to test methods, or do best practices dictate reusing Widgets as much as possible?

Finally, how much granularity should exist between asserts/fails and test methods? A purist might argue that 1-and-only-1 assertions should exist inside a test method, however under that paradigm, if Widget has a getter called getBuzz(), I'll end up with 20 different test methods for getBuzz() with names like

@Test
public void testGetBuzzWhenFooIsNullAndFizzIsNonNegative() { ... }

As opposed to 1 method that tests a multitude of scenarios and hosts a multitude of assertions:

@Test
public void testGetBuzz() { ... }

Thanks for any insight from some JUnit maestros!

Pattern

Interesting question. First of all - my ultimate test pattern configured in IDE:

@Test
public void shouldDoSomethingWhenSomeEventOccurs() throws Exception
{
    //given

    //when

    //then
}

I am always starting with this code (smart people call it BDD).

  • In given I place test setup unique for each test.

  • when is ideally a single line - the thing you are testing.

  • then should contain assertions.

I am not a single assertion advocate, however you should test only single aspect of a behavior. For instance if the the method should return something and also has some side effects, create two tests with same given and when sections.

Also the test pattern includes throws Exception. This is to handle annoying checked exceptions in Java. If you test some code that throws them, you won't be bothered by the compiler. Of course if the test throws an exception it fails.

Setup

Test setup is very important. On one hand it is reasonable to extract common code and place it in setup()/@Before method. However note that when reading a test (and readability is the biggest value in unit testing!) it is easy to miss setup code hanging somewhere at the beginning of the test case. So relevant test setup (for instance you can create widget in different ways) should go to test method, but infrastructure (setting up common mocks, starting embedded test database, etc.) should be extracted. Once again to improve readability.

Also are you aware that JUnit creates new instance of test case class per each test? So even if you create your CUT (class under test) in the constructor, the constructor is called before each test. Kind of annoying.

Granularity

First name your test and think what use-case or functionality you want to test, never think in terms of:

this is a Foo class having bar() and buzz() methods so I create FooTest with testBar() and testBuzz(). Oh dear, I need to test two execution paths throughout bar() - so let us create testBar1() and testBar2().

shouldTurnOffEngineWhenOutOfFuel() is good, testEngine17() is bad.

More on naming

What does the testGetBuzzWhenFooIsNullAndFizzIsNonNegative name tell about the test? I know it tests something, but why? And don't you think the details are too intimate? How about:

@Test shouldReturnDisabledBuzzWhenFooNotProvidedAndFizzNotNegative`

It both describes the input in a meaningful manner and your intent (assuming disabled buzz is some sort of buzz status/type). Also note we no longer hardcode getBuzz() method name and null contract for Foo (instead we say: when Foo is not provided). What if you replace null with null object pattern in the future?

Also don't be afraid of 20 different test methods for getBuzz(). Instead think of 20 different use cases you are testing. However if your test case class grows too big (since it is typically much larger than tested class), extract into several test cases. Once again: FooHappyPathTest, FooBogusInput and FooCornerCases are good, Foo1Test and Foo2Test are bad.

Readability

Strive for short and descriptive names. Few lines in given and few in then. That's it. Create builders and internal DSLs, extract methods, write custom matchers and assertions. The test should be even more readable than production code. Don't over-mock.

I find it useful to first write a series of empty well-named test case methods. Then I go back to the first one. If I still understand what was I suppose to test under what conditions, I implement the test building a class API in the meantime. Then I implement that API. Smart people call it TDD (see below).

Recommended reading:

what book would you recommend to improve one's c# style of writing? I know Code Complete has a few tips on style and organizing code but it's not specific to c#.

I would also recommend Clean Code by Robert Martin. Yes, it's not C#-specific, and yes, it will improve one's C# style of writing. It might be a good idea to continue with Agile Software Development, Principles, Patterns, and Practices book by the same author.

And here is 1 hour video from uncle Bob at Øredev conference Clean Code III: Functions

PS: Shameless plug. I developed a site which answers exactly this question: "Which book is of higher importance in given area?". I get the data from Amazon, and draw a network of books. The more links one book has the higher its importance. Thanks to this site I also found "Agile Principles, Patterns, and Practices in C#", again by Robert Martin, but I prefer the original book.

CLR Via C# by Jeffrey Richter contains all the 2.0 patterns you need to follow in order to produce good code. Helped me immensely.

Effective C# by Bill Wagner, as well as the sequel, More Effective C#.

Elements of C# Style is a good primer.

While it may not go into as much detail as other books that are available but I've definetly got my moneys worth from it - highly recommended.

C# Concisely very thorough

What coding standards in java should a programmer definitely follow for a more readable code?

What's a good way to leverage TDD to drive out thread-safe code? For example, say I have a factory method that utilizes lazy initialization to create only one instance of a class, and return it thereafter:

private TextLineEncoder textLineEncoder;
...
public ProtocolEncoder getEncoder() throws Exception {
    if(textLineEncoder == null)
        textLineEncoder = new TextLineEncoder();
    return textLineEncoder;
}

Now, I want to write a test in good TDD fashion that forces me to make this code thread-safe. Specifically, when two threads call this method at the same time, I don't want to create two instances and discard one. This is easily done, but how can I write a test that makes me do it?

I'm asking this in Java, but the answer should be more broadly applicable.

In the book Clean Code there are some tips on how to test concurrent code. One tip that has helped me to find concurrency bugs, is running concurrently more tests than the CPU has cores.

In my project, running the tests takes about 2 seconds on my quad core machine. When I want to test the concurrent parts (there are some tests for that), I hold down in IntelliJ IDEA the hotkey for running all tests, until I see in the status bar that 20, 50 or 100 test runs are in execution. I follow in Windows Task Manager the CPU and memory usage, to find out when all the test runs have finished executing (memory usage goes up by 1-2 GB when they all are running and then slowly goes back down).

Then I close one by one all the test run output dialogs, and check that there were no failures. Sometimes there are failed tests or tests which are in deadlock, and then I investigate them until I find the bug and have fixed it. That has helped me to find a couple of nasty concurrency bugs. The most important thing, when facing an exception/deadlock that should not have happened, is always assuming that the code is broken, and investigating the reason ruthlessly and fixing it. There are no cosmic rays which cause programs to crash randomly - bugs in code cause programs to crash.

There are also frameworks such as http://www.alphaworks.ibm.com/tech/contest which use bytecode manipulation to force the code to do more thread switching, thus increasing the probability of making concurrency bugs visible.

C#, nUnit, and Rhino Mocks, if that turns out to be applicable.

My quest with TDD continues as I attempt to wrap tests around a complicated function. Let's say I'm coding a form that, when saved, has to also save dependent objects within the form...answers to form questions, attachments if available, and "log" entries (such as "blahblah updated the form." or "blahblah attached a file."). This save function also fires off emails to various people depending on how the state of the form changed during the save function.

This means in order to fully test out the form's save function with all of its dependencies, I have to inject five or six data providers to test out this one function and make sure everything fired off in the right way and order. This is cumbersome when writing the multiple chained constructors for the form object to insert the mocked providers. I think I'm missing something, either in the way of refactoring or simply a better way to set the mocked data providers.

Should I further study refactoring methods to see how this function can be simplified? How's the observer pattern sound, so that the dependent objects detect when the parent form is saved and handle themselves? I know that people say to split out the function so it can be tested...meaning I test out the individual save functions of each dependent object, but not the save function of the form itself, which dictates how each should save themselves in the first place?

The simple answer is that code that you are trying to test is doing too much. I think sticking to the Single Responsibility Principle might help.

The Save button method should only contain a top-level calls to delegate things to other objects. These objects can then be abstracted through interfaces. Then when you test the Save button method, you only test the interaction with mocked objects.

The next step is to write tests to these lower-level classes, but thing should get easier since you only test these in isolation. If you need a complex test setup code, this is a good indicator of a bad design (or a bad testing approach).

Recommended reading:

  1. Clean Code: A Handbook of Agile Software Craftsmanship
  2. Google's guide to writing testable code

G'day,

Inspired by a comment I made in my answer to this question on commenting Perl regexps I was wondering the following.

When you are working on older, old, bloody ancient, code do you update comments that are out of sync with the code or do you just update the code and ignore the comments that are already "miles out" from the reality of the current code?

I guess basically approaching things from the "broken window" syndrome?

BWS basically says that people just say "stuff it" and don't take care to fix errors that are there if they see that people, already involved with the system in question, didn't care enough to fix these sorts of things. A totally pervasive mind set IMHO!

I'd be interested to see what other people "at the coalface" do.

cheers,

Recently I started following more of Uncle Bob's Clean Code advices and I'm trying to transform comments into functions that enclose (extract) the commented code in a function that is at least as meaningful as the comment it replaces.

I am using a single activity and multiple fragments(screenshot attached) within the same activity to provide a seamless navigation. But after implementing the latest toolbar and navigation view, it seems hard to handle the navigation and home buttons. I am having trouble with the following things.

  • Managing the Hamburger/Back button at left top. Toggling the icon and functionality to Menu and Back nav.
    • Page title - Changing the page titles whenever a fragment in pushed and popped.

I have tried several things like overriding onBackPressed(), setHomeAsUpIndicator, popping fragments manually. Earlier i was using ActionBarDrawer toggle to handle this but it is failing somehow now. I checked the google samples they seem to use separate activities at most of the places.

Can anyone guide me how to implement a proper back navigation to handle the NavigationView, Back button in inner fragments and page titles? I am using AppCompatActivity, android.app.Fragment, NavigationView and Toolbar.

Fragment 1 -> Fragment 2 -> Fragment 3

tl;dr

Watch this: https://youtu.be/ANpBWIT3vlU

Clone this: https://github.com/shredderskelton/androidtemplate.

This is a really common problem and one that I've overcome by creating a kind of template project which I use whenever I start a new Android project. The idea is to abstract as much of the logic that handles the back button, the 'hamburger' indicator and fragment management into reusable classes:

Start by creating a BaseActivity and BaseFragment class. This is where you are going to as much of the reusable code as possible.

Lets start with your BaseActivity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fragmentManager = getSupportFragmentManager();
    fragmentHandler = new AddFragmentHandler(fragmentManager);
    fragmentManager.addOnBackStackChangedListener(backStackListener);
}

The FragmentManager is the key to owning the back stack, so you need to listen for changes to the back stack from here. The AddFramentHandler is a little class I cooked up to make it easier to add Fragments, from Fragments. More on that later.

@Override
public void onBackPressed() {
    if (sendBackPressToDrawer()) {
        //the drawer consumed the backpress
        return;
    }

    if (sendBackPressToFragmentOnTop()) {
        // fragment on top consumed the back press
        return;
    }

    //let the android system handle the back press, usually by popping the fragment
    super.onBackPressed();

    //close the activity if back is pressed on the root fragment
    if (fragmentManager.getBackStackEntryCount() == 0) {
        finish();
    }
}

onBackPressed is where most of the magic happens. You notice the plain text formatting of the methods.. I'm a huge Clean Code fan - if you need to write comments, your code isn't clean. Basically you need to really have a central place where you can run to when you're not sure why a back button press is not happening the way you expect. This method is that place.

private void syncDrawerToggleState() {
    ActionBarDrawerToggle drawerToggle = getDrawerToggle();
    if (getDrawerToggle() == null) {
        return;
    }
    if (fragmentManager.getBackStackEntryCount() > 1) {
        drawerToggle.setDrawerIndicatorEnabled(false);
        drawerToggle.setToolbarNavigationClickListener(navigationBackPressListener); //pop backstack
    } else {
        drawerToggle.setDrawerIndicatorEnabled(true);
        drawerToggle.setToolbarNavigationClickListener(drawerToggle.getToolbarNavigationClickListener()); //open nav menu drawer
    }
}

This is the other key part of the BaseActivity. Basically this method checks whether you are at the root fragment and sets up the indicator accordingly. Notice that it changes the listener depending on how many fragments are in the back stack.

Then there is the BaseFragment:

@Override
public void onResume() {
    super.onResume();
    getActivity().setTitle(getTitle());
}

protected abstract String getTitle();

The code above shows how the title is handled by the fragments.

If I have a function with a ton of conditionals what is the best way to organize it?

What I am worried about is someone else coming into the code and understanding what is going on. Even though the example is simple imagine that the conditional is very complex.

For an example:

public void function(string value, string value2)
{
    if (value == null)
        return;

    if (value2 == value)
        DoSomething();
}

or

public void function(string value, string value2)
{
    if (value != null)
    {
        if (value2 == value)
            DoSomething();
    }
}

or

public void function(string value, string value2)
{
    if (value != null && value2 == value)
        DoSomething();
}

May I recommend the book Clean Code by Robert C. Martin which provides a great set of heuristics for writing readable and maintainable code.

Now another option would be to extract the conditional into another private function and name it so that it describes your intent. It doesn't work too well with the supplied code as it's generic but it would look something like:

public void function(string value, string value2)
{
    if (valuesAreValidAndEqual(value, value2))
    {
        DoSomething();
    }
}

private void valuesAreValidAndEqual(string value, string value2)
{
    return value != null && value2 == value;
}

Clearly this is more useful if the variable names and function names are related to your domain.

I'm reading some books about coding standard in Java. I always loved beautiful and clean code.

But there are some things that bother me. For example, a method name should start with a lowercase word, and if it has a second word, it should be start with a uppercase character. But the standard for variables is the same thing. I think this is a little confusing.

So I'm asking you guys, what's your coding standard in Java? Like:

  1. How do you name objects, methods, classes, etc.
  2. If you have more than one object from same class, how do you name the second one?
  3. If you have one object in the argument of a method and you have another object from the same class inside this method, how you do name both of them?
  4. What is the best trade-off for performance/code beauty, a lot of small methods, or some longer methods?
  5. Feel free to say something more. =)
  1. Mostly following the Java code convention.
  2. I try to not make it matter what kind of class an object is. If I for instance have five different strings, the name of each variable should describe what information/content the variable represents, and not that is is a string.
  3. I find it often silly to try coming up with variations of a variable just because it exists both as a method argument and a class variable. I mostly use the same name with this syntax this.theVariable = theVariable
  4. A method should be as short as possible: as few lines as possible, and as few nested levels as possible (i.e. max one if-statement, and not ifs inside ifs etc.)
  5. Robert Martin's Clean Code is highly recommended!

I have array which contain many flights info I want only five lowest price.

First I make loop to sort array by price

second I print first five array

but it take more time..how to reduce this big time?

foreach ($flights_result->json_data['response']['itineraries'] as $key => $value)
{
    $mid[$key] = $value['price']['totalAmount'];
}

//Sort the data with mid descending
//Add $data as the last parameter, to sort by the common key
array_multisort($mid, SORT_ASC, $flights_result->json_data['response']['itineraries']);

// print 5 arrays
foreach ($flights_result->json_data['response']['itineraries'] as  $value)
{
    echo 'departureTime:' . $value['inboundInfo']['departureTime'] . '</br>';
    echo 'layoverInMin:' . $value['inboundInfo']['layoverInMin'] . '</br>';
    //      // loop echo 

    foreach ($value['inboundInfo']['flightNumbers'] as $flightNumbers)
    {
        echo 'flightNumbers  :' . $flightNumbers . '</br>';
    }

    echo 'durationInMin:' . $value['inboundInfo']['durationInMin'] . '</br>';
    echo 'localDepartureTimeStr:' . $value['inboundInfo']['localDepartureTimeStr'] . '</br>';
    echo ' arrivalTime:' . $value['inboundInfo']['arrivalTime'] . '</br>';
    echo ' numStops:' . $value['inboundInfo']['numStops'] . '</br>';

    ////     loop 
    foreach ($value[' inboundInfo']['flightClasses'] as $flightClasses)
    {
        echo 'flightClasses name :' . $flightClasses['name'] . '</br>';
        echo 'flightClasses fareClass :' . $flightClasses['fareClass'] . '</br>';
    }

    echo 'localArrivalTimeStr:' . $value['inboundInfo']['localArrivalTimeStr'] . '</br>';
    //      loop  echo

    foreach ($value[' carrier'] as $carrier)
    {
        echo 'carrier name :' . $carrier['name'] . '</br>';
        echo 'carrier code :' . $carrier['code'] . '</br>';
    }

    echo 'amount:' . $value['price']['amount'] . '</br>';
    echo ' totalAmount :' . $value['price']['totalAmount'] . '</br>';
    echo 'pricePerPassenger:' . $value['price']['pricePerPassenger'] . '</br>';
    echo 'currencyCode: ' . $value['price']['currencyCode'] . '</br>';
    echo 'totalPricePerPassenger: ' . $value['price']['totalPricePerPassenger'] . '</br>';
    echo 'includesTax: ' . $value['price ']['includesTax'] . '</br>';
    echo 'destinationCountryCode:' . $value[' destinationCountryCode'] . ' </br> -------- </br>';

    $count++;
    if ($count > 2)
    {
        break;
    }
}

array example

Array
(
    [0] => Array
        (
            [ecpcRank] => 0
            [inboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1381448400000
                    [layoverInMin] => 1359
                    [flightNumbers] => Array
                        (
                            [0] => DL3672
                            [1] => EK204
                            [2] => EK923
                        )

                    [durationInMin] => 2360
                    [airportsExpanded] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => JFK
                            [3] => DXB
                            [4] => DXB
                            [5] => CAI
                        )

                    [localDepartureTimeStr] => 2013/10/10 18:40 -0500
                    [airports] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => DXB
                            [3] => CAI
                        )

                    [arrivalTime] => 1381590000000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/12 17:00 +0200
                )

            [location] => Array
                (
                    [0] => Array
                        (
                            [code] => CAI
                            [name] => Cairo
                        )

                    [1] => Array
                        (
                            [code] => DXB
                            [name] => Dubai
                        )

                    [2] => Array
                        (
                            [code] => PHL
                            [name] => Philadelphia
                        )

                    [3] => Array
                        (
                            [code] => JFK
                            [name] => New York J F Kennedy
                        )

                    [4] => Array
                        (
                            [code] => MXP
                            [name] => Milan Malpensa
                        )

                )

            [carrier] => Array
                (
                    [0] => Array
                        (
                            [name] => Delta Air Lines
                            [code] => DL
                        )

                    [1] => Array
                        (
                            [name] => US Airways
                            [code] => US
                        )

                    [2] => Array
                        (
                            [name] => Emirates
                            [code] => EK
                        )

                    [3] => Array
                        (
                            [name] => Egyptair
                            [code] => MS
                        )

                )

            [bookingType] => WEBSITE
            [price] => Array
                (
                    [name] => 
                    [nameOTA] => 
                    [description] => 
                    [amount] => 26280
                    [totalAmount] => 26280
                    [pricePerPassenger] => 26280
                    [currencyCode] => EGP
                    [totalPricePerPassenger] => 26280
                    [includesTax] => 1
                )

            [generatedDate] => 1380212804686
            [providerId] => emirates.com
            [id] => MS703[CAI-MXP],EK205[MXP-JFK],US3407[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI]
            [originCountryCode] => EG
            [bookingCode] => 13600077136293253
            [destinationCountryCode] => US
            [outboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1380958800000
                    [layoverInMin] => 1050
                    [flightNumbers] => Array
                        (
                            [0] => MS703
                            [1] => EK205
                            [2] => US3407
                        )

                    [durationInMin] => 1940
                    [airportsExpanded] => Array
                        (
                            [0] => CAI
                            [1] => MXP
                            [2] => MXP
                            [3] => JFK
                            [4] => JFK
                            [5] => PHL
                        )

                    [localDepartureTimeStr] => 2013/10/05 09:40 +0200
                    [airports] => Array
                        (
                            [0] => CAI
                            [1] => MXP
                            [2] => JFK
                            [3] => PHL
                        )

                    [arrivalTime] => 1381075200000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/06 11:00 -0500
                )

        )

    [1] => Array
        (
            [ecpcRank] => 0
            [inboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1381448400000
                    [layoverInMin] => 1359
                    [flightNumbers] => Array
                        (
                            [0] => DL3672
                            [1] => EK204
                            [2] => EK923
                        )

                    [durationInMin] => 2360
                    [airportsExpanded] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => JFK
                            [3] => DXB
                            [4] => DXB
                            [5] => CAI
                        )

                    [localDepartureTimeStr] => 2013/10/10 18:40 -0500
                    [airports] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => DXB
                            [3] => CAI
                        )

                    [arrivalTime] => 1381590000000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/12 17:00 +0200
                )

            [location] => Array
                (
                    [0] => Array
                        (
                            [code] => CAI
                            [name] => Cairo
                        )

                    [1] => Array
                        (
                            [code] => PHL
                            [name] => Philadelphia
                        )

                    [2] => Array
                        (
                            [code] => DXB
                            [name] => Dubai
                        )

                    [3] => Array
                        (
                            [code] => JFK
                            [name] => New York J F Kennedy
                        )

                )

            [carrier] => Array
                (
                    [0] => Array
                        (
                            [name] => Delta Air Lines
                            [code] => DL
                        )

                    [1] => Array
                        (
                            [name] => Emirates
                            [code] => EK
                        )

                )

            [bookingType] => WEBSITE
            [price] => Array
                (
                    [name] => 
                    [nameOTA] => 
                    [description] => 
                    [amount] => 28183
                    [totalAmount] => 28183
                    [pricePerPassenger] => 28183
                    [currencyCode] => EGP
                    [totalPricePerPassenger] => 28183
                    [includesTax] => 1
                )

            [generatedDate] => 1380212804689
            [providerId] => emirates.com
            [id] => EK928[CAI-DXB],EK203[DXB-JFK],DL6122[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI]
            [originCountryCode] => EG
            [bookingCode] => 13600077139546083
            [destinationCountryCode] => US
            [outboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1380966900000
                    [layoverInMin] => 947
                    [flightNumbers] => Array
                        (
                            [0] => EK928
                            [1] => EK203
                            [2] => DL6122
                        )

                    [durationInMin] => 2118
                    [airportsExpanded] => Array
                        (
                            [0] => CAI
                            [1] => DXB
                            [2] => DXB
                            [3] => JFK
                            [4] => JFK
                            [5] => PHL
                        )

                    [localDepartureTimeStr] => 2013/10/05 11:55 +0200
                    [airports] => Array
                        (
                            [0] => CAI
                            [1] => DXB
                            [2] => JFK
                            [3] => PHL
                        )

                    [arrivalTime] => 1381093980000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/06 16:13 -0500
                )

        )

)

The first thing to understand is which part of you code takes long to execute. A quick and dirty but simple way is to use your logger. Which I assume you are using already to log all your other information you want to keep as your code runs, such as memory usage, disc usage, user requests, purchases made etc.

Your logger can be a highly sofisticated tool (just google for "loggin framework" or the likes) or as simple as message writer to your file. To get a quick start, you can using something like that:

class Logger {
  private $_fileName;
  private $_lastTime;

  public function __construct ($fileName) {
    $this->_fileName = $fileName;
    $this->_lastTime = microtime(true);
  }

  public function logToFile ($message) {
    // open file for writing by appending your message to the end of the file
    $file = fopen($this->_fileName, 'a');
    fwrite($file, $message . "\n");
    fclose($file);
  }

  // optional for testing - see your logs quickly without bothering with files
  public function logToConsole($message) {
    echo $message;
  }

  // optional $message to add, e.g. about what happened in your code
  public function logTimePassed ($message = '') {
    $timePassed = microtime(true) - $this->_lastTime;
    //$this->logToConsole("Milliseconds Passed since last log: " . $timePassed . ", " . $message . "\n");
    $this->logToFile("Milliseconds Passed since last log: " . $timePassed . ", " . $message . "\n");
    // reset time
    $this->_lastTime = microtime(true);
  }
}

// before your code starts
$myLogFileName = 'my-logs'; // or whatever the name of the file to write in
$myLogger = new Logger($myLogFileName);

// ... your code goes ...

// after something interesting
$myLogger->logTimePassed(); // log time since last logging

// ... your code continues ...

// after something else, adding a message for your record
$myLogger->logTimePassed("after sorting my flight array"); 

Now you can go over your code and place your loggers at all crucial points after anything that may potentially take too long. Add your messages to know what happened. There can potentially be many places for delays. Usually array manipulations done in-memory are blazing fast. But more attention needs to be paid for more time consuming operations such as:

  • File reading/ writing, directory access
  • Database access
  • HTTP requests

For instance, http requests - are your echos being sent immediately to browser over a network? Are they being sent every time in the loop? If yes, you probably want to avoid it. Either save them into array as indicated by other answers, or use Output Buffering.

Further to minimize http requests to your server, you can try to put more functions on the client side and use ajax to only retrieve what is really needed from the server.

Also don't forget about things that are hidden. For instance, I see object property access:

$flights_result->json_data

How is this object implemented? Is it in-memory only? Does it call to outside services? If yes, that may be your culprit. Then you have to work on optimizing that. Reducing the number of queries by caching them, optimizing your data so you only need to query the changes, etc. All this depends on the structure of you application and may have nothing to do with the rest of your code. If you want any help on that, you obviously need to put this information in your question.

Basically anything that is not done entirely in memory can cause delays. As for the in-memory operations, unless your data are huge or your operations are intense, their effect will likely be negligible. Still if you have any doubt, simply place your loggers at all "suspicious" places.


Now to your specific code, it mixes all sort of things, such that outside object access, array value access, array sorting, echo outputs, maybe other things that are hidden. This makes it hard even to know where to place your time loggers.

What would make it much easier, is to use object oriented approach and follow, among others, the Principle of Separating Concerns (google on that). That way your objects and their methods will have single responsibilities and you will easily see who does what and where to place your loggers.

I can't highly enough recommend the legendary book by "Uncle Bob" to learn more about it. I presume your code comes from inside a function. According to Uncle Bob:

The first rule of functions is that they should be small. The second rule is that they should be smaller than that.

and

Functions should do one thing. They should do it well. They should do it only.

When splitting your code into more functions, you are forced to give those functions meaningful names that can greatly improve readability of your code. Needless to say, all functions not intended for use outside the class, should be private, so you can easily re-use your classes via inheritance.


There is a lot that can be done, but just to get you started, here are some ideas:

  • Encapsulate your data array into an object with methods only doing there what you need. Something like that:

    class Itineraries {
      private $_itineraryArray;
    
      public function __construct(array $itineraryArray) {
        $this->_itineraryArray = $itineraryArray;
      }
    
      public function getNCheapest ($number) {
        $this->_sortByPrice();
        $result = array();
        for ($i=0; $i< $number; $i++) {
          $result[] = $this->_itineraryArray[$i];
        }
        return $result;
      }
    
      private function _sortByPrice() {
        $prices = $this->_getPriceArray();
        array_multisort($prices, SORT_ASC, $this->_itineraryArray);
      }
    
      private function _getPriceArray () {
        foreach ($this->_itineraryArray as $entry) {
          $this->_getPrice($entry);  
        }
      }
    
      private function _getPrice($entry) {
        return $entry['price']['totalAmount']; // or whatever it is
      }
    }
    
    //Then you instantiate your object:
    $myItineraries = new Itineraries($flights_result->json_data['response']['itineraries']); // or whatever
    

Notice that should your array structure completely change, you'll only need to adjust the method _getPrice and the single line to instantiate your object! The rest of your code will remain intact!

This is a part of your Model Layer in the Model-View-Controller paradigm. You can google on that to find lots of information. The model knows how to handle its data but knows nothing about the source of them, no browser output, no http requests etc.

  • Then everything responsible for generating user output goes into your View Layer or into so-called Presenter Layer, where you have other objects dealing with it. All your 'echo's will go here. Something like that:

    class Presenter {
      public function outputNCheapest ($myItineraries, $number) {
        $outputData = $myItineraries->getNCheapest ($number);
        echo $this->generateOutput($outputData);
      }
    
      private function _generateOutput($outputData) {
        $html = '';
        // your html string is generated
        return $html;
      }
    }
    

However, I am personally against generating HTML on the server. It is just a waste of bandwidth and the time of your users waiting for response. Every time I am waiting for my browser to reload the whole page, I want the developer to read this. You can output JSON instead of HTML and request it with ajax or via other ways on the client side.

Furthermore, your user's browser can cache some of the data instead of requesting them again, and decide what to ask for. That will further minimize the delay for your users, which at the end of the day is precisely what you are concerned with.

I'm kind of torn between these two error-handling models:

  1. Create a boolean Error and a string ErrorMessage property for your object. Catch all exceptions internally in the object's methods and pass the messages along using conditional logic from the caller, ie:

    Dim o As New MyObject
    o.SomeMethod()
    If Not o.Error Then
        'Do stuff'
    Else
        Dim msg As String = o.ErrorMessage
        'do something with message'
    End If
    
  2. Throw exceptions in your object and handle them on the outside with Try Catch logic:

    Dim o As New MyObject
    Try
       o.SomeMethod()      
       'Do stuff'
    Catch ex As Exception
        Dim msg As String = ex.ErrorMessage
        'do something with message'
    End Try
    

To me, it seems like the same amount of code either way, except that you have property code for the Error and ErrorMessage properties. However, you also can tell when an error occurs without having to check for exceptions. Which pattern should I go with?

I have decided to go with throwing exceptions instead of using error/return codes. I just recently looked really hard into this.

The #1 reason to throw exceptions is there is a possibility you can forget to check the error code. If you don't check it, then you will continue working while the error exists. With exceptions though, if you forget to handle them, then the exception will raise to the top and stop all processing. It is better for this to happen than to continue after unknown errors have occurred.

For more info check out the Exception chapter in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, Second Edition by Addison-Wesley.

Joel Spolsky actually prefers error/return codes over exceptions but a lot of people disagree with him. Joel's post in favor of return codes can be found here. Check out this blog post and all of the comments with some good discussion regarding this subject.

Prefer #2. For details, see this excerpt on Exception Throwing from the development of Microsoft's excellent Framework Design Guidelines, as Dennis mentioned. Note especially the section on Exceptions and Performance.

Short version:

Do not return error codes.

Do report execution failures by throwing exceptions.

Do not use exceptions for normal flow of control.

I highly recommend reading the book for a full discussion, complete with commentary from a number of the Microsoft luminaries.

Exceptions should be used when something exceptional has happened.

e.g. you are passed a null (nothing) object when you expect one.

Uncle Bob recommends Exceptions over Error codes in his book Clean code.

He says

The problem with these [error codes] approaches is that they clutter the caller. The caller must check for errors immediately after the call. Unfortunately it's easy to forget. For this reason it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.

I'm looking for a rather arbitrary answer, so this might more be a discussion. I'm wondering what the best practise for commenting my C# code in visual studio is. Right now I'm using the triple /// to generate the xml and use sand castle to build a chm or html file. But my problem is that I use code comments for two reasons:

  1. When other developers are using my code they can read the documentation, both intellisence and the chm. or html file.
  2. But I also use commenting as reminders to myself. So I can remember my thoughts when I come back half a year later, to some complex methods.

How can both goals be accomplished without interfering with each other, and in the same time be a quick task, not taking a lot of coding time?

The best advice I can give you is:

Don't comment bad code; rewrite it!

If methods are very complex, than most of the time you are doing something wrong (not always, but very close to always). Writing readable code is hard, but pays of, because writing good comments that you (or your colleges) will understand a year later is hard as well (and perhaps even harder). Ways to make things clear is by breaking methods up in smaller well named methods and using very clear variable names.

A book that has helped me a lot in creating better code was Robert Martins Clean Code. If you haven't read it, please do. And let all the developers in your company read it.

Good luck.

In the past 2 months that I have been learning PHP, I have identified more than two styles people use to comment code! I haven't seen much consistency... which I think usually means artists at work. So I wondered: what are the valid ways to comment which are still readable/practical? Seeing all the valid possibilities in 1 place side by side will provide the overview that I am looking for to improve commenting

/*
|  This is what I now use (5chars/3lines) I name it star*wars
\*

Quoting the Manual on Comments:

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:

<?php
    echo 'This is a test'; // This is a one-line c++ style comment
    /* This is a multi line comment
       yet another line of comment */
    echo 'This is yet another test';
    echo 'One Final Test'; # This is a one-line shell-style comment
?>

In general, you will want to avoid using comments in your sourcecode. To quote Martin Fowler:

When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.

which means something like

// check if date is in Summer period
if ($date->after(DATE::SUMMER_START) && $date->before(DATE::SUMMER_END)) {

should be rewritten to

if ($date->isInSummerPeriod()) { …

Another comment type you will sometimes encounter is the separator comment, e.g. something like

// --------------------------------------------

or

################################################

Those are usually indicative that the code they are used in is doing too much. If you find this in a class, check the responsibility of the class and see if some parts of it are better refactored into a standalone class.

As for API docs, the common notation is PHPDoc, e.g.

/**
 * Short Desc
 *
 * Long Desc
 * 
 * @param  type $name description
 * @return type       description
 */
 public function methodName($name) { …

I would argue that you can omit Short and Long Desc if the remaining method signature clearly communicates what it does. However, that requires a certain discipline and knowledge in how to actually write Clean Code. For instance, the following is totally superfluous:

/**
 * Get the timestamp property
 *
 * The method returns the {@link $timestamp} property as an integer.
 * 
 * @return integer the timestamp
 */
 public function getTimestamp() { …

and should be shortened to

/**
 * @return integer
 */
 public function getTimestamp() { …

Needless to say, whether you go for full API docs or not also depends on the project. I'd expect any framework I can download and use to have full API docs. The important thing is just that whatever you decide to do, do it consistently.

I realize this is partially subjective, but I'm generally curious as to community opinion and have not been able to successfully find an existing question that tackles this issue.

I am in a somewhat religious debate with a fellow coworker about a particular Select statement in a L2EF query.

.Select(r =>
{
    r.foo.Bar = r.bar;
    r.foo.Bar.BarType = r.Alpha;
    if (r.barAddress != null)
    {
        r.foo.Bar.Address = r.barAddress;
        r.foo.Bar.Address.State = r.BarState;
    }
    if (r.baz != null)
    {
        r.foo.Bar.Baz = r.baz;
        if (r.bazAddress != null)
        {
            r.foo.Bar.Baz.Address = r.bazAddress;
            r.foo.Bar.Baz.Address.State = r.BazState;
        }
    }
    return r.foo;
})

Caveats:

  • This is Linq-to-Entities
  • This is after the work in the DB as been performed and returned
  • The input parameter r is anonymous

Personally, I'm of the opinion that (a) the select clause should not be altering values, it should merely project. His counter argument is that he's not altering anything, he's just making sure everything is properly initialized as a result of the DB query. Secondly, I think once he starts getting into full code blocks and return statements, it's time to define a method or even a Func<T, U> and not do all of this inline. The complicator here is, again, the input is anonymous, so a type would need to be defined. But nevertheless, we are still debating the general point if not the specific.

So, when does a lambda expression do too much? Where do you draw the fuzzy line in the sand?

Get your coworker and yourself a copy of Robert C. Martin's "Clean code" book, and compare "Uncle Bob's" coding style to your Linq statement. You will get plenty of ideas on how to refactor it.

It's been one and a half years since I graduated from university with a degree in computer science and engineering. I joined a company which does maintenance of a large enterprise software system. First I thought with time I'll become a very good programmer. But now I'm beginning to realize that things are not exactly that way.

What I need is some advice/tips/ideas on becoming a competent programmer when you don't have a lot of chances on the job to design or code from scratch.

In your situation (not writing new code from scratch at your job) probably the best thing you can do is start a hobby programming project. Pick a problem that's interesting to you and solve it.

At work you can write unit tests and refactor existing code as you fix bugs and add new features.

I'd also recommend reading at least one of

No book will give you the same skills you'll learn by writing code yourself, but these three give a lot of good advice, and will expose you to a lot of the knowledge that comes with the collective experience of the authors. There's a lot in these books that I wish I'd known earlier in my career.

Finally, check out the Programmer Competency Matrix. Probably not many of us score high in all categories, so it's a good place to look to find ideas for areas where you might improve.

Aprroach 1:

public static void SendMail(string from, string to, string subject, string body)
{
   if(String.IsNullOrWhiteSpace(from))
      throw new ArgumentNullOrWhiteSpaceException("from");

   if(String.IsNullOrWhiteSpace(to))
      throw new ArgumentNullOrWhiteSpaceException("to");

   var msg = new MailMessage(from, to, subject, body) { IsBodyHtml = true };

   using(var smtp = new SmtpClient())
      smtp.Send(msg);
}

Approach 2:

public static void SendMail(string from, string to, string subject, string body)
{
   var msg = new MailMessage(from, to, subject, body) { IsBodyHtml = true };

   using(var smtp = new SmtpClient())
      smtp.Send(msg);
}

Why would I validate the parameters in approach 1, and not just wait for MailMessage to throw an exception (approach 2), telling me that I have passed a empty from or to value, to the constructor?

So why would I throw my own exception?

erm... are you SURE in 100% that var msg = new MailMessage(from, to, subject, body) { IsBodyHtml = true };

will throw those exceptions? approach 2 is undefined behavior. how should this be unit tested?

what does SendMail("","","") do? extacly? its not clear from the second approach.

you COULD add a comment. but WHY? thats not clean code

arroach 1 clearly defines where the function is going to fail. and how it is going to handle failures. your code should make clear what is does, not comments.

P.S.

throw new ArgumentNullOrWhiteSpaceException("from"); is throwed in your SendMail function, closest to the source of the problem.

if you use approach 2 only god knows how deep in your call hirerchy it will be caught if at all.

also you could improve this by writting somethinf like:

ArgumentNullOrWhiteSpaceException("from - this is usually caused if poo is not bared by poo in goo"); ` that could simplify your life a few month later.

Possible Duplicate:
How many parameters are too many?

I was just writing a function that took in several values and it got me thinking. When is the number number of arguments to a function / method too many? When (if) does it signal a flawed design? Do you design / refactor the function to take in structs, arrays, pointers, etc to decrease the amount of arguments? Do you refactor the data coming in just to decrease the number of arguments? It seems that this could be a little less applicable in OOP designs, though. Just curious to see how others view the issue.

EDIT: For reference the function I just wrote took in 5 parameters. I use the definition of several that my AP Econ teacher gave me. More than 2; less than 7.

Robert C. Martin (Uncle Bob) recommends 3 as a maximum in Clean Code: A Handbook of Agile Software Craftsmanship

I don't have the book with me at the moment but his reasoning has to do with one, two and, to a lesser extent, three argument functions reading well and clearly showing the purpose of the function.

This of course goes hand in hand with his recommendation of very short, well named functions that adhere to the Single Responsibility Principal.

I am trying to convert an if statement to switch cases (for readability)

1) I've read switch statements are aweful in general - Is that true? http://stackoverflow.com/questions/6097513/switch-statement-inside-a-switch-statement-c

2) The statement goes like this:

switch (Show)
                {
                    case Display.Expense:
                        if (expected.EXPENSE != true)
                            break;
                    case Display.NonExpense:
                        if (expected.EXPENSE == true)
                            break;
                    case Display.All:
                        //Code
                        break;
                }

Error is:

Control cannot fall through from one case label ('case 1:') to another

This is the original if statement:

if ((Show == Display.All) || (expected.EXPENSE == true && Show == Display.Expense) || (expected.EXPENSE == false && Show == Display.NonExpense))
{
    //Code
}

Use if statements and extract complex conditions into methods, e.g

if (ShowAll() || ShowExpense())
{
}

Remember about OOP and polymorphism every time you write such 'switch', adding another case to that code will be a nightmare

see this and similar (C++) instructions about converting switches

P.S if you are interested in making your code clean and readable, consider reading Smalltalk Best Practice Patterns by Kent Beck and/or Clean Code by Uncle Bob I really enjoyed both of them, highly recommend.

I came across different interview where question was asked to me why encapsulation is used? Whose requirement actually is encapsulation? Is it for users of program? Or is it for co-workers? Or is it to protect code from hackers?

Encapsulation helps in isolating implementation details from the behavior exposed to clients of a class (other classes/functions that are using this class), and gives you more control over coupling in your code. Consider this example, similar to the one in Robert Martin's book Clean Code:

public class Car
{
//...
public float GetFuelPercentage() { /* ... */ };

//...

private float gasoline;
//...
}

Note that the client using the function which gives you the amount of fuel in the car doesn't care what type of fuel does the car use. This abstraction separates the concern (Amount of fuel) from unimportant (in this context) detail: whether it is gas, oil or anything else.

The second thing is that author of the class is free to do anything they want with the internals of the class, for example changing gasoline to oil, and other things, as long as they don't change its behaviour. This is thanks to the fact, that they can be sure that no one depends on these details, because they are private. The fewer dependencies there are in the code the more flexible and easier to maintain it is.

One other thing, correctly noted in the underrated answer by utnapistim: low coupling also helps in testing the code, and maintaining those tests. The less complicated class's interface is, the easier to test it. Without encapsulation, with everything exposed it would be hard to comprehend what to test and how.

To reiterate some discussions in the comments:

  • No, encapsulation is not the most important thing in OOP. I'd dare even to say that it's not very important. Important things are these encouraged by encapsulation - like loose coupling. But it is not essential - a careful developer can maintain loose coupling without encapsulating variables etc.. As pointed out by vlastachu, Python is a good example of a language which does not have mechanisms to enforce encapsulation, yet it is still feasible for OOP.

  • No, hiding your fields behind accessors is not encapsulation. If the only thing you've done is write "private" in front of variables and then mindlessly provide get/set pair for each of them, then in fact they are not encapsulated. Someone in a distant place in code can still meddle with internals of your class, and can still depend on them (well, it is of course a bit better that they depend on a method, not on a field).

  • No, encapsulation's primary goal is not to avoid mistakes. Primary goals are at least similar to those listed above, and thinking that encapsulation will defend you from making mistakes is naive. There are just lots of other ways to make a mistake beside altering a private variable. And altering a private variable is not so hard to find and fix. Again - Python is a good example for sake of this argument, as it can have encapsulation without enforcing it.

If I have a large .NET method, I want to know if it is good practice to split it up into multiple methods or not. My concerns are: 1 - Is there any point creating a method if it will only be called once?
2 - If I'm calling a private method from within my class, I try not to use instance variables. Is this good or bad practice? For example:

var a, b;
public void TestMe
{
   FirstTest(a,b);
}
private void FirstTest(paramA, paramB)
{
         //code here with passed in parameters
}

//instead of:
private void FirstTest()
{
      //code here with instance variables a,b
}  

edit: replace global with instance

To quote from Clean Code (an excellent book), a method should do one thing and one thing only. If you're doing multiple things in a method, then it probably means that you need to extract that logic into a separate method. It makes it a lot easier to follow the code as well. So I would say

Question 1: Yes break it up (separation of concern).

Question 2: In general I think it is a bad practice to have global variables unless you absolutely need to. As far as the general question of using the private property (instance variable) by itself over the public getter, I don't see any advantage by using the getter. For example, consider:

function someFunc() {
  anotherFunc(this.a, this.b);
}

function anotherFunc(int paramA, int paramB) {
  //do stuff with paramA and paramB
}

versus

function someFunc() {
  anotherFunc();
}

function anotherFunc() {
  //do stuff with this.a and this.b
}

At some point you'd have to refer to the instance variable by using this. So I don't see an advantage. After all, you are inside your class, so you have complete access to private members.

I'm trying to make my code easily understood by future readers.

I've always had issues with how to word my if statement comments to make it the most understandable.

Maybe it seems trivial, but it's something that's always bothered me

Here's an example:

if ( !$request ) {
    $request = $_SERVER['REQUEST_URI'];
}

Here are some way I can think of commenting it

// If request doesn't exist
if ( !$request ) {
    // Set request to current request_uri
    $request = $_SERVER['REQUEST_URI'];
}

// Check for a request
if ( !$request ) {
    $request = $_SERVER['REQUEST_URI'];
}

// Request doesn't exist
if ( !$request ) {
    // Set request
    $request = $_SERVER['REQUEST_URI'];
}

Not the best example, but the way I see it there are infinite ways to word it.

I've never really worked on a team so I don't have much experience on other people reading my code.

What are your experiences on the best way to word that to make it readable for future coders.

Read the book Clean Code by Robert Martin.

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Comments should be only used to explain concepts that the code can't explain itself.

As said before, maybe your example is a bit too simple in order really have a relevant comment on it, but here are a couple of general suggestions:

  • usually is easier to read "positive" conditions rather than negations (not condition)

  • don't hesitate to extract methods that will have a detailed name that will communicate the intent and avoid thus the need of some of the comments. In your case, say you create:

    function getRequest( $req ) {
        if( isset( $req ) ) {
            return $req;
        } else {
            return $_SERVER['REQUEST_URI'];
        }
    }
    

    but again, we need a more appropriate example, in your case it might be overkill

  • must read :

in private and in companies it is over and over again a problem that I or we developers comment in fact our code but generally nobody knows exactly how the code of the whole project works together. When I write my own code and the project is getting bigger I sometimes have this problem too. Although I write tons of comments, after 3 months you don't know what the whole thing exactly does, that means how the different methods and classes work together.
How do you solve this in your company or in private (if there is just marginal project development and no requirements specification). Or do you have always such a good project development with contract document and requirements specification that you don't have to worry about that?

Good question. Part of what you are asking relates to code maintainability. In my view the two main things you can do to improve this are:-

  • Write some design documentation
  • Develop maintainable and clearly written code

From past experience the first item is very often neglected on software projects due to time constraints, but I think that if you can produce at least a class diagram of your system, then this is worth a lot in terms of understanding how objects interract when you revisit the code in a few months. Depending on the complexity, then sequence diagrams can also be useful. Producing this documentation will also be of benefit to new members of the team, in quickly having an overview of how the software is structured.

I can't stress enough the importance of writing clear and maintainable code. My eyes were recently opened when I read Clean Code by Robert Martin. You owe it to yourself and your fellow developers to read at least the first couple of chapters in this book. That alone will immediately improve the readability and maintainability of your code.

The idea is that the code should read almost like a narrative, where methods follow in a logical order, are short, appropriately named, and take few parameters. Doing this almost eliminates the need for code comments, and improves the code structure.

Code complete can explain the solution to your problem better than I ever could.

I try to refactor a code so that it will use separate methods to do some calculations. Just to make it clear.

What I want to know is, is it a good practice or a bad one to write a separate method to find out a simple thing like a number is odd or even ?

The original code is ,

    int n = 11;
    if (n % 2 == 0) {
        System.out.println("Not selected");
    } else {
        boolean isPrime = true;
        if (n == 0 || n == 1) {
            isPrime = false;
        } else {
            int i = 2;
            double a = Math.sqrt(Math.abs(n));
            while (i <= a) {
                if (n % i == 0) {
                    isPrime = false;
                }
                ++i;
            }
        } 
        if(isPrime){
            System.out.println("Prime it is");
        }
    }

The refactored code is,

    int n = 11;
    if (isEven(n)) {
        System.out.println("Not selected");
    } else { 
        if (isPrime(n)) {
            System.out.println("Prime it is");
        }
    }

public static boolean isEven(int n) {
    return n % 2 == 0 ? true : false;
}

public static boolean isPrime(int n){
    if(n==0 || n==1)return false;        
    int i=2;
    double a = Math.sqrt(Math.abs(n));
    while(i<=a){
        if(n%i==0){
            return false;
        }            
        ++i;
    }
    return true;
}

It's generally considered good practice to break code down into separate methods for things like readability, length, or cyclomatic complexity, especially if you are not changing how the code works.

Boolean expressions, like what you have extracted, are often good choices for a quick extract function refactor. It allows a reader of the code base to know why a boolean expression is important or what it does by being able to read a descriptive function name versus complex domain related boolean math which they may not care to know the intricate details of.

A good book about commonly considered best practices in Java for code organization is a book called Clean Code. It's a pretty easy and enjoyable read, I would suggest it.

The project I'm working on has just hit 4200 lines in the main C# file, which is causing Intellisense to take a few seconds (sometimes up to 6 or so) to respond, during which Visual Studio locks up. I'm wondering how everyone else splits their files and whether there's a consensus.

I tried to look for some guides and found Google's C++ guide but I couldn't see anything about semantics such as function sizes and file sizes, maybe it's there - I haven't looked at it for a while.

So how do you split your files? Do you group your methods by the functions they serve? By types (event handlers, private/public)? And at what size limit do you split functions?

Edit: To clarify, the application in question handles data - so it's interface is a big-ass grid, and everything revolves around the grid. It has a few dialogs forms for management but it's all about the data. The reason why it's so big as there is a lot of error checking, event handling, and also the grid set up as master-detail with 3 more grid for each row (but these load on master row expanded). I hope this helps to clarify what I'm on about.

In the classic book "Structured Programming" Dijkstra once wrote a section entitled: "On our inability to do much." His point was simple. Humans aren't very smart. We can't juggle more than a few concepts in our minds at one time.

It is very important to keep your classes and methods small. When a method gets above a dozen lines or so, it should be broken apart. When a class gets above a couple of hundred lines, it should be broken apart. This is the only way to keep code well organized and manageable. I've been programming for nearly 40 years, and with every year that has gone by, I realize just how important the word "small" is when writing software.

As to how you do this, this is a very large topic that has been written about many different times. It's all about dependency management, information hiding, and object-oriented design in general. Here is a reading list.

We're an agile project of about 20 developers organized in 2-3 teams, doing no pair programming, a little bit team rotation and a lot of peer reviews. Most of us are addicted to the "green status bar" of IDE code analysis (most of use idea, some eclipse and netbeans, resharper is idea functionality in the .net world).

We are considering dropping the formal code standard altogether. Being agile, we try to ditch all things that give us nothing, and quite frankly it just sits there looking like a relic from the past.

The argument is that code quality enforced by the regular code standard simply is the wrong metric; placement of braces has little or nothing to do with quality. IDE code analysis, findbugs and peer reviews creates the quality we want

Arguably we have some "hallway" code standards that you don't want to break if you expect to eat lunch with the others (nobody uses hard tabs, we have some limits!)

Are code standards a relic from the waterfall past ?

P.s. I'm not tagging this language-agnostic because I believe there is a substantial difference to what tools can do in java/c# compared with other languages.

Edit: I would not consider choice of external libraries to be part of the code standard. For most core libraries this is most certainly a centralized decision.

I believe a standard is essential, however how formal it needs to be defined depends on how well your team communicates. If your team is working effectively and reviewed code is clean and readable then you can probably relax the formality but completely removing it will make it more difficult for new members.

The main objective of a coding standard should be to set expectations to the developers in a team (especially new members), some of this can be done with static analysis tools. If these are used right from the beginning as a habit then this can be effective, otherwise providing a document can be a great starting point for new developers. You don't want the standard\guidelines to be a surprise during their first code review.

Part of this purpose is to encourage clean, readable code by guiding developers in the style they use (see http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).

Over time, as you have already witnessed, the standard becomes an internalised responsibility of each developer and relies less on external ceremony (formal documentation of the standard).

You may want to consider reducing the emphasis of the formal coding standard on hard format issues e.g. brace placement, format for variable names etc, which can be demonstrated easily by static analysis and more on style guidelines e.g. naming, size of methods\classes, clarity of purpose etc.

I am writing a program that checks the number of parameters of a methods and prints out a warning message (its a codesmell program) If there are more than what the standard is, the problem is that I don't know what the agreed number is. I have looked around and not had any luck. Can anyone tell me or at least point me in the right direction?

My honest opinion is there is no defined limit to the number of parameters. My personal preference is not to have more than 3 or at least 4 since this can effect readability and mental mapping (difficult to remember more than 4 parameters). You can also have a quick peep at Uncle Bob's Clean Code and Steve McConnell's Code Complete regarding this.

There is a similar thread in SO see When a method has too many parameters?

I did some searching on here and haven't found anything quite like this, so I'm going to go ahead and ask. This is really more about semantics than an actual programming question. I'm currently writing something in C++ but the language doesn't really matter.

I'm well aware that it's good programming practice to keep your functions/methods as short as possible. Yet how do you really know if a function is too long? Alternately, is it ever possible to break functions down too much?

The first programming language I learned (other than Applesoft BASIC, which doesn't count...) was 6502 assembly language, where speed and optimization is everything. In cases where a few cycle counts screws up the timing of your entire program, it's often better to set a memory location or register directly rather than jump to another subroutine. The former operation might take 3 or 4 cycles, while, altogether, the latter might take two or three times that.

While I realize that nowadays if I were to even mention cycle counts to some programmers they'd just give me a blank look, it's a hard habit to break.

Specifically, let's say (again using C++) we have a private class method that's something like the following:

int Foo::do_stuff(int x) {
    this->x = x;
    // various other operations on x
    this->y = this->x;
}

I've seen some arguments that, at the very least, each set of operations should be its own function. For instance, do_stuff() should in theory be named to set_x(int x), a separate function should be written for the set of operations performed on class member x, and a third function should be written to assign the final value of class member x to class member y. But I've seen other arguments that EVERY operation should have its own function.

To me, this just seems wrong. Again, I'm looking at things from an internal perspective; every method call is pushing an address on the stack, performing its operations, then returning from the subroutine. This just seems like a lot of overhead for something relatively simple.

Is there a best practice for this sort of thing or is it more up to individual judgment?

After reading Clean Code: A Handbook of Agile Software Craftsmanship which touched on almost every piece of advice on this page I started writing shorter. Not for the sake of having short functions but to improve readability and testability, keep them at the same level of abstraction, have them do one thing only, etc.

What I've found most rewarding is that I find myself writing a lot less documentation because it's just not necessary for 80% of my functions. When the function does only what its name says, there's no point in restating the obvious. Writing tests also becomes easier because each test method can set up less and perform fewer assertions. When I revisit code I've written over the past six months with these goals in mind, I can more quickly make the change I want and move on.

I'm a computer science student, and I'm just starting to write relatively larger programs for my coursework (between 750 - 1500 lines). Up until now, it's been possible to get by with any reasonable level of modularization and object oriented design. However, now that I'm writing more complex code for my assignments I'd like to learn to write better code.

Can anyone point me in the direction of some resources for learning about what sort of things to look for when designing your program's architecture so that you can make it as modularized as possible?

Read Clean Code by Robert Matin

I'm looking for a way to refactor a log if/else if/else statement that also has a bit of nesting. The blocks also use quite a few common objects. My aim is to break the code apart to manageable units extracted to different classes and make it pluggable in case I need to cover a new condition.

Here's some dummy code to illustrate:

List<ValidationResult> validationResults = new ...;
Inspector inspector = commonInspector;
bool additionalOp = commonFlag;
HashSet<Thing> thingsToCheck = theThings;
foreach (var thing in thingsToCheck)
{
    if (IsCandy(thing) && thing.IsWrapped && thing.IsHard)
    {
        var inspected = inspector.Inspect(thing.Value);
        if (inspected != thing.Value)
        {
            validationResults.Add(new ...);
            if (additionalOp)
            {
                thing.Taste();
            }
        }
    }
    else if (IsChocolate(thing))
    {
        var sweet = (Sweet)thing;
        List<BadCalories> badCalories;
        while (var calorie in sweet.Calories)
        {
            if (calorie.IsGood)
                continue;
            badCalories.Add(calorie);
        }

        foreach (var badCal in badCalories)
        {
            var inspected = inspector.Inspect(badCal.Value);
            if (inspected != badCal.Value)
            {
                validationResults.Add(new ...);
                if (additionalOp)
                {
                    badCal.Taste();
                }
            }
        }
    }
    else
    {
        if(thing ...)
        else if (thing ...)
    }

I read a bunch of articles/SO posts of various patterns/practices that may apply, but the code's dependencies complicate it a bit for me to apply the concepts. It doesn't help that I've been looking at the code somewhat too closely for a while now so it's hard to break out from micro-managing to a birds eye view.

You could break the large scope blocks into separate functions.

if(IsHardWrappedCandy(thing))
  ValidateHardWrappedCandy(thing);
else if (IsChocolateCandy(thing))
  ValidateChocolateCandy(thing);

There is also interitance, where you would create candy classes and encapsulate behavior:

public abstract class CandyBase
{
    public abstract void Validate();
}
public class HardWrappedCandy : CandyBase
{
  public override void Validate()
  {
     // TODO: Validation logic
  }
}

Then your code would be:

foreach(var candy in candies)
   candy.Validate();

Of course you will need to standardize parameters and such, but you get the idea.

Read the book Clean Code, it has a lot of great ideas on how to refactor. http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

I'm still relatively new to iOS development and also an absolute stranger to any kind of testing that is not compile, run, and check whatever comes to your mind.

This is obviously a weakness on any developer's profile and I'm decided to get ride of it now that interesting, real projects are coming my way.

In my quest to look for the best approach to go from 0 to 100 as soon (and well) as possible I'm coming to the specialized community to get your feedback.

At the same time I'm asking for your tips I'm also getting into Amazon to look for well-reviewed books on the subject and Google to get the rest. I'm just coming here to gather the feedback of those willing to spare a minute or to so I can probably hit jackpot with a great advise and better plan my learning strategy.

Thats right. For my job testing and test driven development is indispensable.

I often use Java and JUnit, but for Objective-C and XCode I think this screencast is a very good start: http://qualitycoding.org/objective-c-tdd/

Since I watch this screencast I use OCHamcrest and OCMockito (both explaind in this screencast) as well as SenTestingKitAsync for testing asynchronous functions.

I think the Clean Code book is a must have for every developer. There is a chapter about testing.

Is it right to use goto in this code? Are there any alternatives?

return ExecuteReader(cmd, reader =>
{
    List<BEPartnership> partnerhip = null;

    //Partnership
    if (!((SqlDataReader) reader).HasRows)
        goto exit;

    partnerhip = 
        new List<BEPartnership>{new BEPartnership().GetFromReader(reader)};

    //Customers
    if (!reader.NextResult() && !((SqlDataReader) reader).HasRows)
        goto exit;

    foreach (BEPartnership p in partnerhip)
        p.Partner = new BECustomer().GetFromReader(reader);

    //Contracts
    if (!reader.NextResult() && !((SqlDataReader) reader).HasRows)
        goto exit;

    List<BEContractB2B> contracts = new List<BEContractB2B>();
    contracts.Add(new BEContractB2B().GetFromReader(reader));
    // contracts = new BEContractB2B().GetFromReader2(reader).ToList();

    exit:
    return partnerhip;
});

Gotos are the root of all evil. Try refactoring the method as follows:

return ExecuteReader(cmd, reader =>
{
    var sqlReader = (SqlDataReader)reader;

    if (!sqlReader.NextResult())
    {
        return null;
    }

    var partnerhip = new BEPartnership().GetFromReader(sqlReader);

    if (sqlReader.NextResult())
    {
        partnerhip.Partner = new BECustomer().GetFromReader(sqlReader);
    }

    if (sqlReader.NextResult())
    {
        // What are you doing with contact?
        var contact = new BEContractB2B().GetFromReader(sqlReader));
        // perhaps: partnership.Partner.Contact = contact;
    }

    return new List<BEPartnership> { partnerhip };
});

When you are starting to write clean code, there is absolutely no need for gotos. Even worse, they make your code unreadable. Take care of your code, since it is read many more times than it is written. Here is a good book about clean code.

It is very common in Ruby to see methods that receive a hash of parameters instead of just passing the parameters to the method.

My question is - when do you use parameters for your method and when do you use a parameters hash?

Is it right to say that it is a good practice to use a parameter hash when the method has more than one or two parameters?

if you have more than 2 arguements. you should start thinking of using hash. This is good practise clearly explained in clean code link text

I've been using CodeIgniter for a while, and have a decent knowledge of MVC, PHP etc.

However, I'm finding it hard to adhere to the Fat Model Skinny Controller ethos.

I've seen a lot about it; including what pseudo code to include in each file, but no actual examples. (Please link to some articles if I've missed any obvious ones!)

I'm finding it hard to move the form logic to a model. For instance, I am using a custom library for my auth system, which has it's own model. Should I then make a site user Model to log users in? Or should I just make a site Model to do that? Or a form Model?

To help me out, can anyone advise me on how to skinnify this Controller? I realise it's a lot of code, but simple pointers would be great. (Please note, I've only just written this code, so it hasn't been refactored much, but it should give a good example of how some of my methods are getting out of hand.)

public function register()
{
    session_start();
    if ($this->tf_login->logged_in())
    {
        redirect('profile');
    }
    if ($_GET['oauth'] == 'true')
    {
        $type = $_GET['type'];
        try 
        {
            $token = $this->tf_login->oauth($type, '', 'email');
        }
        catch (TFLoginCSRFMismatchException $e)
        {
            $this->tf_assets->add_data('error_message', $e->getMessage());
        }
        catch (TFLoginOAuthErrorException $e)
        {
            $this->tf_assets->add_data('error_message', $e->getMessage());
        }
        if ($token)
        {
            $user_details = $this->tf_login->call('https://graph.facebook.com/me?fields=email,first_name,last_name,username&access_token=' . $token);
            $user_details_decoded = json_decode($user_details);
            if ($user_details_decoded->email)
            {
                try 
                {
                    $id = $this->tf_login->create_user($user_details_decoded->username,
                    md5($user_details_decoded->username . time()),
                    $user_details_decoded->email,
                    '',
                    TRUE,
                    TRUE);
                }
                catch (TFLoginUserExistsException $e)
                {
                    try
                    {
                        if ($this->tf_login->oauth_login($type, $user_details_decoded->email, $token))
                        {
                            $this->session->set_flashdata('success_message', 'You have successfully logged in.');
                            redirect('profile');
                        }
                        else
                        {
                            $this->session->set_flashdata('error_message', 'An account with these details exists, but currently isn\'t synced with ' . $type . '. Please log in to sync the account.');
                        }
                    }
                    catch (Exception $e)
                    {
                        $this->session->set_flashdata('error_message', $e->getMessage());
                    }
                }
                catch (TFLoginUserNotCreated $e)
                {
                    $this->tf_assets->add_data('error_message', 'You could not be registered, please try again.');
                }
                if ($id)
                {
                    $this->tf_login->add_user_meta($id, 'first_name', $user_details_decoded->first_name);
                    $this->tf_login->add_user_meta($id, 'surname', $user_details_decoded->last_name);
                    $this->tf_login->sync_accounts($id, $type, $token);
                    $this->session->set_flashdata('success_message', 'Welcome ' . $this->input->post('first_name', TRUE) . ' ' . $this->input->post('surname', TRUE) . '. Your account has been sucessfully created. You will shortly receive an email with a verification link in.');
                    redirect('login');
                }
            }
            else
            {
                $this->session->set_flash_data('error_message', 'You could not be logged in, please try again.');
            }
        }
        // Redirect to clear URL
        redirect(current_url());
    }

    if ($this->form_validation->run() !== FALSE)
    {
        try
        {
            $id = $this->tf_login->create_user($_POST['username'], $_POST['password'], $_POST['email'], '', FALSE);
        }
        catch (Exception $e)
        {
            $this->tf_assets->add_data('error_message', $e->getMessage());
        }
        if ($id)
        {
            $this->tf_login->add_user_meta($id, 'first_name', $_POST['first_name']);
            $this->tf_login->add_user_meta($id, 'surname', $_POST['surname']);
            if ($this->tf_login->register_verification_email())
            {
                $this->session->set_flashdata('success_message', 'Welcome ' . $this->input->post('first_name', TRUE) . ' ' . $this->input->post('surname', TRUE) . '. Your account has been sucessfully created. You will shortly receive an email with a verification link in.');
                redirect('login');
            }
            else
            {
                $this->tf_login->login_user($id);
                $this->session->set_flashdata('success_message','Your account has been sucessfully created.');
                redirect('profile');
            }
        }
        else
        {
            $this->tf_assets->add_data('error_message', $this->tf_login->get_errors());
        }
    }
    if (validation_errors())
    {
        $this->tf_assets->add_data('error_message', validation_errors());
    }
    $this->tf_assets->set_content('public/register');
    $this->tf_assets->add_data('page_title', "Register");
    $this->tf_assets->render_layout();
}

Thanks in advance!

From what I can tell, most or all of this code belongs in a controller or component, so I don't think your problem is Model/Controller confusion.

The code is difficult to read, however, because of the deep nested structures and the failure to break out specific tasks into their own methods. The main refactoring you would benefit from here is creating new private methods to separate out the discrete subtasks that you are performing. This is has the additional important benefit of clarifying the high-level structure of your current method. So you would end up with something that looked like (just to give you a rough example):

public function register()
{
    session_start();
    if ($this->tf_login->logged_in())
    {
        redirect('profile');
    }
    if ($_GET['oauth'] == 'true')
    {
        $this->oauthRegister();
    }

    $this->normalRegister();
}

Similarly, the oatuhRegister method and normalRegister methods would be broken down into smaller methods themselves, so that when you were completely finished each method would be adhering to the SRP and would probably be fewer than 10 lines of code. This will drastically improve the readability and maintainability of your code. I'd also recommend checking out Clean Code, which makes a strong argument for keeping your method short.

More specifically making HTML, Java, and python more readable? Does anyone have suggestions for this programming student?

Have a look at this book: Clean Code: a handbook of agile software craftsmanship. It is all about making code readable and understandable.

Are there other example projects like the Northwind Starters kit around that show you 'best practices' (layers, unit tests, mocking data, o/r mapping tools, ...) in architecture of ASP.NET development?

Or links to good and clear resources or documentation? (MSDN is a good reference but no good as tutorial)

  • are there example projects around addressing Visual Studio2008 and/or the AdventureWorks database?

thx, Lieven Cardoen

Microsoft has a whole slew of sample projects, white papers, etc. covering best practices on a variety of topics. Many of these are focused on ASP.NET but you'll probably want to go right to the MS Best Practices center. They also published a book covering the topic but it is quite old and I wouldn't recommend it any longer.

Of course, you may want to go right to the source for an overall approach to coding best practices and for that I'd recommend Martin and Martin's Agile Principles, Patterns and Practices in C#. I'm just finishing up Robert Martin's Clean Code and, while a fair amount is obvious, it is well written, has tons of examples and has helped push me to be more "craftsmanlike" in my approach to coding.

The last thing is that I consider good Unit Testing to be one of the bedrock "best practices" for any developer. I recommend Pragmatic Unit Testing by Hunt and Thomas there.

That should get you going!

I would recommend the book Building a Web 2.0 Portal with ASP.NET 3.5 by Omar Al Zabir.
His blog on ASP.NET Ajax and .NET 3.5 is also very valuable.

Here's a question that comes up again and again in C++ class implementation. I'm curious about what people's thoughts are here. Which code do you prefer and why?

class A
{
public:
    /* Constructors, Destructors, Public interface functions, etc. */ 
    void publicCall(void);

private:
    void f(void);

    CMyClass m_Member1;
};

with

void A::publicCall(void)
{
    f();
}

void A::f(void)
{
    // do some stuff populating  m_Member1
}

Or the alternative:

class A
{
public:
    /* Constructors, Destructors, Public interface functions, etc. */ 
    void publicCall(void);

private:
    void f(CMyClass &x);

    CMyClass m_Member1;
};

with

void A::publicCall(void)
{
    f(m_Member1);
}

void A::f(CMyClass &x)
{
    // do some stuff to populate x, 
    // locally masking the fact that it's really m_Member1
}

I think I always prefer the second one because then f can then operate on any instance of CMyClass but, that said, I have lots of code where the first is perfectly valid since f will only ever operate on m_Member1 and I'm really breaking it into two functions to make the code more readable.

Yes, this is more of a discussion question than an "answer" question, but I'm more interested in the reasoning. I'll mark as an answer a response that gives good reasoning or a good criterion.

Also, keep in mind that this is just a toy example. The class will be bigger than this in reality and thus organization is important.

Isn't f in the second example better of as a static function of A or global function or, maybe, a member function of CMyClass?

Of course, there are cases where you're better off sending the argument every time you call that function, but why would you resend it when you already have on CMyClass object in the A object. If you need both CMyClass objects to interact, you may be better off adding it to CMyClass member function list, rather than to A.

Also, as Clean Code states, you're better off with functions without any arguments, than with ones with arguments. When another programmer tries to read the function, it must decipher/pay attention to the second parameter, besides the function name.

How do you write code that is easily read by other people and who have had no hand in writing any part of it?

Buy & read Code Complete 2. There's loads of stuff in there about writing easy to read / maintain code.

I don't think it's a subjective question, but it's too broad! It's not just about commenting and giving good variables names. It deals with how humans comprehends code. So your system must be implemented in a way that the reader can easily construct a mental model of its design in two way:

  • Top-down: assuming the user knows the system domain, he tends to make assumptions on how it would be implemented, so he'll scan the system packages and classes looking for entities he can identify. Giving good names to your classes and properly modularizing it would help very much.

  • Bottom-up: once the user reaches a portion of code he'll start navigation from there, building chunks of knowledge. If your system has low cohesion and lots of implicit dependencies the user will be lost.

Kent Beck adopts three principles: Communication, Simplicity and Flexibility. Of course, sometimes you'll have to trade simplicity for flexibility, and vice-versa.

This could go on and on. The answer to this question fits in a large book. As @rmbarnes suggested, buy and read Code Complete 2. I also suggest Implementation Patterns by Kent Beck - its highly related to your question.

You may want to take a look at Clean Code by Robert C. Martin. It offers up a lot of useful practices for ensuring your code is readable.

Additionally, if your code is supported by a number of unit tests that thoroughly test your code, it offers a way for your user to understand the code by looking at what the tests are doing. You will also find that if you follow the Test Driven Development process, and you write tests for each bit of functionality, your functions tend to be small, do one thing only and do it well, and tend to flow more like a story than simply a large complex web of "stuff".

Tests tend to stay up-to-date more than comments. I often ignore comments anymore due to simple fact that they become obsolete very quickly.

Since everyone else said pretty much what I'm thinking when I read this question, I'll just share two books related to this subject that you might be interested in reading. These books use open source code examples to explain how to read and write high quality code. In addition to Code Complete, I think they are valuable resources when you want to write good code in any language.

I am a mid level developer. Currently I work in C# ASP.NET but I have worked in PHP, classic ASP, and a tiny bit in Java (would like to get more into this in the future). I am looking for a few suggestions on good books to help me continue growing in my coding techniques.

Basically a book with lots of best practices, coding tricks, rarely used but very useful features and operators (e.g. the ?? operator), stuff like that. I am NOT looking for a book to teach me a specific language. I don't particularly care about what language the code samples are in but C or Java would probably be best. The suggestions don't need to be limited to pure code objects either. Books with information about database connection management ect. would be good.

Thanks for your suggestions.

For your java Skills:

and in general

I strongly recommend to read Effective Java before reading Clean Code. -- Because it will make you more sensitive for a few (I personal belive not so optimal) code changes suggested in clean code.

The first book that comes to mind for me is Code Complete. It's fantastic. Absolutely required reading for a serious developer.

If by rarely used stuff, you think Bitwise operations, Hacker's Delight is supposed to be really well regarded.

I am new to Java and was wondering how I would go about implementing ActionListener code in my project. I am aware of inner classes and the implementation the ActionListener interface, but going down that road makes the code look more messy than it probably should.

Would I write another class ActionCode that implements ActionListener and extends GUI or what road would you suggest and why?

What's your best practice advise on that and where can I find those guidelines? (The JavaDoc seems to explain the basic implementation of ActionListeners, but doesn't seem to have any model how to organize large/medium projects).

Code style can be a matter of personal taste, but modern literature suggests it's more than that. Let the chapter on Classes in Clean Code show you the way.

Classes Should Be Small!

The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. No, we’re not going to repeat the exact same text from the Functions chapter. But as with functions, smaller is the primary rule when it comes to designing classes. As with functions, our immediate question is always “How small?” With functions we measured size by counting physical lines. With classes we use a different measure. We count responsibilities...

The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change. This principle gives us both a definition of responsibility, and a guidelines for class size. Classes should have one responsibility—one reason to change...

The problem is that too many of us think that we are done once the program works. We fail to switch to the other concern of organization and cleanliness. We move on to the next problem rather than going back and breaking the overstuffed classes into decoupled units with single responsibilities. At the same time, many developers fear that a large number of small, single-purpose classes makes it more difficult to understand the bigger picture. They are concerned that they must navigate from class to class in order to figure out how a larger piece of work gets accomplished. However, a system with many small classes has no more moving parts than a system with a few large classes. There is just as much to learn in the system with a few large classes. So the question is: Do you want your tools organized into toolboxes with many small drawers each containing well-defined and well-labeled components? Or do you want a few drawers that you just toss everything into?

Every sizable system will contain a large amount of logic and complexity. The primary goal in managing such complexity is to organize it so that a developer knows where to look to find things and need only understand the directly affected complexity at any given time. In contrast, a system with larger, multipurpose classes always hampers us by insisting we wade through lots of things we don’t need to know right now. To restate the former points for emphasis: We want our systems to be composed of many small classes, not a few large ones. Each small class encapsulates a single responsibility, has a single reason to change, and collaborates with a few others to achieve the desired system behaviors.

So, based on these heuristics, Nested Classes break SRP. They should almost never happen. Instead, have your GUI classes include instance members of the ActionListeners they register. Keep the listeners in a separate *.listener package. Use interfaces to make them replaceable (Strategy Pattern) wherever deemed effective.

I am using code complexity metric, and line of code(per function).
This keeping the code short and readable.

What code metrics you using?

I measure code quality by WTF's per minute: http://blog.energizedwork.com/2008/08/wtfs-per-minute.html

This specific image comes from the book Clean Code: http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 It has a lot of info on how to keep your code clean and maintainable. Including guidelines on function length.

I am very sorry, but I am unable to define this "thing" that I'm trying to figure out.

When writing functions we can take different approaches, I have made some "placeholder" examples:

--------A---------
getImageSmall();
getImageLarge();
getTextSmall();
getTextLarge();
--------B---------
getImage('small');
getImage('large');
getText('small');
getText('large');
--------C---------
get('image','small');
get('image','large');
get('text','small');
get('text','large');
--------D---------
get(array('type'=>'image','size'=>'small'));
get(array('type'=>'image','size'=>'large'));
get(array('type'=>'text','size'=>'small'));
get(array('type'=>'text','size'=>'large'));
--------E---------
get('{"type":"image","size"=>"small"}');
get('{"type":"image","size"=>"large"}');
get('{"type":"text","size"=>"small"}');
get('{"type":"text","size"=>"large"}');

I could of included objects too, but I prefer to keep it simple for now.

The array in "D" is a php array to show the difference between example "E" that uses json.

You can probably see how the approach gradually shifts from one way of thinking to another, where function definitions turn to information exchange. This does not mean that the "get" function is a master function that does everything, it might be a messenger function that calls other functions, its sole purpose might be to turn the app into a service.

The questions are:

  • What is this shift in coding style called? (main question)
  • When is it best to use which?
  • Where can I read more about this?

Clarification and comments/questions/answers in order to improve this question are welcome.

Naming function and passing values to functions has always been one of many topics of discussion. I would recommend you to look at what's commonly called "Clean Code". It contains theory for naming and constructing functions. This is a good book to take a look at

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

and check YouTube for Clean Code and you will probably find a few good talks.

My thoughts is that you can do a million different ways when constructing functions. You could, in theory, besides your examples have a function called Get that takes a pointer to a function that returns the type of the thing to get. But the only thing this adds is complexity. What we want to achieve is basically self commenting code that is easy for other people to read and understand. For this, every function should follow set rules in regards to how it is named in accordance to what it performs, what it is allowed to change and return etc. This would make for much easier code for someone to get into.

This goes for classes to. Don't have some class that sets up a million things in it's constructor. If that is needed, then create functions to encapsulate the behavior and call these functions from the constructor.

I have been coding for a few years and still feel that my knowledge is not broad enough to become a professional. I have studied some books related to design patterns, but I know there are many others.

So could somebody list the patterns and principles which you think are good to learn to become a better programmer and more professional?

Programming Languages I work on: C#, Ruby, Javascript.

Encyclopedic knowledge of design patterns will get you nowhere. Plenty of experience applying them will. This will teach you when to use them and when not to.

That said, the original Design Patterns book is still one of my favorites. Pick up other patterns as you go along.

Martin Fowler's Patterns of Enterprise Application Architecture to build up a shared vocabulary with other developers (e.g. Repository, Active Record, Domain Model, Unit of Work).

Douglas Crockford's Javascript: The Good Parts to actually understand how Javascript works.

And I'd really recommend getting into TDD (Test Driven Development). There are a bunch of good TDD books but if you are doing brownfield development (which most of us are) then I'd really recommend Michael Feather's Working Effectively with Legacy Code.

And finally the book that shows you just how refactored and clean code can be: Uncle Bob's Clean Code.

I have been reading a book called Clean Code A Handbook of Agile Software Craftsmanship. The author in the book motivates that a switch statement should be avoided and if it cannot be avoided it should be relegated to factory methods. I have a connection object which is receiving various PDUs (protocol data units). The PDUs vary and they can be received in any order. So if I have a method for example:

public BasePdu ReceiveNext();

because I cannot tell what the packet type is until it has been fully received. In the header of the PDU is an identifier as to which type it should be. This means that the calling method is going to have figure out what the type of the PDU is and based on that call the relevant method to handle it. This sounds like a perfect example for a switch statement. The object that contains the connection I would ideally like to have two threads. One for receiving PDUs and another for servicing a queue of PDUs to be sent.

Now I know that you cannot follow every bit of good advice and that there are just some circumstances which are the exception to the rule. Is this one of them? Or is there a way around this that I just have not yet thought of.

UPDATE:

I hear what a lot of people are saying by creating subclasses of response handlers. The issue is that the containing object has a lot of context and additional information that the handlers would need for example lookups and throttling etc etc. To inject all of this information into subclasses of handlers would be quite a chore to maintain and would also split a lot of logic up when it feels better to be encapsulated in the object that it is in now.

Personally I wouldn't worry about it too much; if it looks like a good place for a switch statement use one. On the other hand this also looks like a situation where you could use a factory method if each PDU type is handled by a class rather than a method. And, accoding to your book, you're allowed you to use switch statements then

I like reading open-source code to see how particular problems have been solved, or simply to study how to create nice and clean code.

I was wondering if there actually was any good book out there that goes through excerpts of different (preferably in Java) open-source projects to show how patterns have been used and implemented, some nifty tricks, etc.?

Update: I took design patterns as an example, but it’s not really what I am after. I read a lot of open-source code, and I often find interesting ways of doing things which I didn’t think of before – my question is whether there is a book that shows some “cool” open-source code, a bit like how Clean Code uses FitNesse code to illustrate refactoring and other points.

Well, you can read just book about open source project, and authors can show what and how. E.g. I read Pro Spring 2.5 and there is even chapter called "Spring Patterns" with explanation of why and how they call files, directories, design patterns they use and invite you to use etc. Probably take a look at the books about open source projects you investigate.

UPDATE (just that paragraph insert to extend answer:) : as I told previously, you can look through the books about open source projects and find there information how this project is developed, architectural issues etc. Once I looked for real good example of "Open/Closed Principle" using, theory is nice but I would not say that it is so clear how to use it. The only book which helped me was Expert Spring MVC and Web Flow (I already pointed you to google books with that chapter I read). I didn't read the whole book, but I am sure it contains a lot of such things (what and how was used to make Spring done). From book Clean Code: A Handbook of Agile Software Craftsmanship I remember that there is a chapter, when they take a code from one open source project and make it better (unfortunately open source does not mean that it is good enough); that book also contain reference to how some other projects where written (e.g. jUnit). I don't know any book, which is completely dedicated to any project, there are just books where is "theory", and books about project which can have some explanation of what is inside. I would recommend books from APress (Pro and Expert series, afaik "beginning" books does not contain such explanation), and Packt Publishing - their main topic is open source.

UPDATE 2 (just can't stop :) Just remembered new series of books from OReilly "Beautiful ...." - I never read it, but I looked through. It actually consists of different stories behind development, real stories from life. I see there is also Beautiful Code: Leading Programmers Explain How They Think - I should contain what you need. Other "beautiful" books can be worth of your time too.

About patterns in general there are a lot of good books, and it depends on what exactly are you looking for. E.g. Head First Design Patterns is quite good to explain common patterns in fun way. If you need more, you can take a look at Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions to see how different applications, systems etc. can be integrated (and how open source projects do it too). Etc. Just specify what patterns or tricks do you want to read about, community will make its suggestion ;)

Some web links out of my bookmarks:

  1. Anti Patterns Catalog - know what you are not going to do!
  2. Design Patterns and Martin Fowler's Catalog - that's shortly about what is good to use and know about
  3. SOA patterns - community site for SOA patterns (integration etc.)

And few more books to take a look at:

  1. Head First Object-Oriented Analysis and Design
  2. Agile Software Development, Principles, Patterns, and Practices
  3. Code Complete - this book is just a bible of how to write code...

people, who develop open source definitely know what are those books about ;)

Hope that helps

UPDATE (25-05-2011) Just found one book, which I definitely going to buy, and I think it perfectly fits your question:

The Architecture of Open Source Applications
enter image description here

Architects look at thousands of buildings during their training, and study critiques of those buildings written by masters. In contrast, most software developers only ever get to know a handful of large programs well — usually programs they wrote themselves — and never study the great programs of history. As a result, they repeat one another’s mistakes rather than building on one another’s successes. This book’s goal is to change that. In it, the authors of twenty-five open source applications explain how their software is structured, and why. What are each program's major components? How do they interact? And what did their builders learn during their development? In answering these questions, the contributors to this book provide unique insights into how they think. Electronic versions of The Architecture of Open Source Applications for e-readers will be available for download soon.

I'm creating a PHP file that does 2 mysql database calls and the rest of the script is if statements for things like file_exists and other simple variables. I have about 2000 lines of code in this file so far.

Is it better practice to include a separate file if a statement is true; or simply type the code directly in the if statement itself?

Is their a maximum number of lines of code for a single file that should be adhered to with PHP?

You may want to read a book like Clean Code by Bob Martin. Here are a few nuggets from that book:

  • A class should have one responsibility
  • A function should do one thing and do it well

With PHP, if you aren't using the Class approach; you're going to run into duplication problems. Do yourself a favor and do some reading on the subject; it'll save you a lot more time in extending and maintenance.

I think making code self-explanatory, without need for comments all around the place, is a big advantage. But could you suggest methods and techniques how to reduce the amount of code, make it more readable and understandable.

Also what do you think are the good techniques for reducing big if statements and nested for loops and other structures which sometimes are hard to understand at the first glance.

Here are few of the things I thought would my C# application more readable and self-explanatory:

  • Converting foreach loops into LINQ statements.
  • Using anonymous function to reduce amount of event handlers.

Any suggestion and/or comments are very welcome. Also suggestions about the books which covers these topics would be appreciated.

I recommend you take a look at Clean Code by Robert C Martin. It's an entire book dedicated to writing readable code. Highly recommended if you ask me.

Resharper is also very useful as it has numerous suggestions for naming, reducing nesting and the like.

I've seen (and searched for) a lot of questions on StackOverflow about premature optimization - word on the street is, it is the root of all evil. :P I confess that I'm often guilty of this; I don't really optimize for speed at the cost of code legibility, but I will rewrite my code in logical manners using datatypes and methods that seem more appropriate for the task (e.g. in Actionscript 3, using a typed Vector instead of an untyped Array for iteration) and if I can make my code more elegant, I will do so. This generally helps me understand my code, and I generally know why I'm making these changes.

At any rate, I was thinking today - in OOP, we promote encapsulation, attempting to hide the implementation and promote the interface, so that classes are loosely coupled. The idea is to make something that works without having to know what's going on internally - the black box idea.

As such, here's my question - is it wise to attempt to do deep optimization of code at the class level, since OOP promotes modularity? Or does this fall into the category of premature optimization? I'm thinking that, if you use a language that easily supports unit testing, you can test, benchmark, and optimize the class because it in itself is a module that takes input and generates output. But, as a single guy writing code, I don't know if it's wiser to wait until a project is fully finished to begin optimization.

For reference: I've never worked in a team before, so something that's obvious to developers who have this experience might be foreign to me.

Hope this question is appropriate for StackOverflow - I didn't find another one that directly answered my query.

Thanks!

Edit: Thinking about the question, I realize that "profiling" may have been the correct term instead of "unit test"; unit-testing checks that the module works as it should, while profiling checks performance. Additionally, a part of the question I should have asked before - does profiling individual modules after you've created them not reduce time profiling after the application is complete?

My question stems from the game development I'm trying to do - I have to create modules, such as a graphics engine, that should perform optimally (whether they will is a different story :D ). In an application where performance was less important, I probably wouldn't worry about this.

I don't really optimize for speed at the cost of code legibility, but I will rewrite my code in logical manners using datatypes and methods that seem more appropriate for the task [...] and if I can make my code more elegant, I will do so. This generally helps me understand my code

This isn't really optimization, rather refactoring for cleaner code and better design*. As such, it is a Good Thing, and it should indeed be practiced continuously, in small increments. Uncle Bob Martin (in his book Clean Code) popularized the Boy Scout Rule, adapted to software development: Leave the code cleaner than you found it.

So to answer your title question rephrased, yes, refactoring code to make it unit testable is a good practice. One "extreme" of this is Test Driven Development, where one writes the test first, then adds the code which makes the test pass. This way the code is created unit testable from the very beginning.

*Not to be nitpicky, just it is useful to clarify common terminology and make sure that we use the same terms in the same meaning.

Where would one find information or just rather good ideas on what is considered proper programming ethics or methodology of how to format the code, comments, or even variable names so that it is easier to read the code at a later time?

Thanks!

The absolute 'must-read' for you is Robert C. Martin's book Clean Code. Do give it a try. It makes some awesome points. I keep recommending to everyone ever since I bought it 6 months ago.

Edit

I thought reading my Amazon review could help :)

According Uncle Bob /source/, every user story should have separated "integrator/controller". Its sounds good because classes will be small and do the only one thing.

But in the real world I didnt see architecture organized in that way. Always if there was eg AccountController it contained all methods related with Account. In Uncle Bob "way" this should be designed just like this:

+Controllers
---+Account
------+DepositMoneyIntoAccount
------+WithdrawalMoneyFromAccount
------+TransferMoneyToAccount

or maybe Im misunderstanding of Uncle Bob? But if not, have someone of you see architecture organized in this look? Its practical in real world?

Regards

You are right, that is the way he wants the project to look like.

Remember his talk "Architecture: The lost years", the architecture should describe its intention(And what better than a Use case?).

At the beginning I was also a bit confused but if we think about it BDD, the philosophy wants to make sure we make understandable software.

I watched the video a couple of times and I probably will again, because it is a new concept and requires study. For me the most important part and more challenging is creating the plugins for the other modules, he talks about a request and response model needed in order to keep the surrounding layers such as front end and database, completely independent from the software.

The final goal of this is that our software can easily replace any addon such as a database or a UI.

Just one more thing I want to mention, I think you are maybe interested. In this interview at the end, he reveals that his next book will be all about this new methodology we are discussing now.

Update

I see in the comments you are talking about calling packages with names such as Boundaries, Interactors...

This is completely ok, in his book clean code that some developers use the name of the pattern in occasions to name the Classes or packages... That is correct, because it is technical terminology that developers should be familiar with. In the same way you know that a class is a builder or a factory by reading its name or package, you can know what interactors or boundaries are. That is correct according to clean code.

By applying the SRP principle you are bound to have a lot of classes. If this works fine for a small project how can you handle and organize the amount of classes on a large project ?

  • how do you organize the folder structure ?
  • how do you remember what you build ?
  • how do you know if others didn't build the same functionally in other class ?

Depends on the project, but if it was something that has a lot of CRUD without much actual business rules, I would go for a structure that is simple, with script files to support that decision. I have done this in the past, and it is super fast, but slow to change. Typically called the Smart UI anti-pattern by Eric Evans:

"Put all the business logic into the user interface. Chop the application into small functions and implement them as separate user interfaces, embedding the business rules into them. Use a relational database as a shared repository of the data. Use the most automated UI building and visual programming tools available [Evans p.77]."

If you are making something with lots of real business rules and have more time, or you expect it to have a long life:

  1. Figure out the tasks of the system, and try to implement those tasks as higher level commands.
  2. Have those higher level commands manipulate low level core classes, and are called from the ui. I have been using the Zend Framework, and I have the controllers call these high level commands, but that is really overkill in most places. I have these classes stored in an Application folder, divided by module (accounting, email, etc).
  3. The lower level classes are held in a Domain folder, which is also split into those same modules as the Application folder. The Domain classes represent the objects being worked on (Email, ClassCredit). These are small, and only do tasks that make sense for that concept.

As for resources to help you further, check out Clean Code by Bob Martin, and Domain-Driven Design (can't post the other link) by Eric Evans. Both books are brilliant, and offer tactical and strategic steps, respectively, to tackling that chaos.

I am building a custom MVC framework using PHP. My problem is when I want to access any model class through the controller class. One way I have seen this done is through a registry design pattern using magic methods such as get and set, though PHP get and set are considered bad practise by some. I have read about dependency injection done through a container, but I can not see this working effectily as the container would have to call the models or it would have to contain the models which would defeat the purpose of MVC and create a massive super class. Singleton is seen as bad practise. Is there any solutions or improvements of the methods I have mentioned. It may just be my understand and knowledge of PHP needs improving.

Currently I have this: router.php (loads up controllor through a GET varible

 <?php

class router {



function __construct() {

    if (file_exists("controller/".$_GET['url']."Controller.php"))  {


       function __autoload($controller) {

           $controlinclude = "controller/".$controller.".php";
            include $controlinclude;

      }
       $control = $_GET['url']."Controller";
        new $control();


    }
    else    {

        // throw exception
    }

}

}
?>

Hope that makes sence

First of all ... Do no put autoloading script in routing mechanism. You are mixing the responsibilities. You will be better off creating a separate class for this based on spl_autoload_register.

Neeext .. do no put complicated operations on constructor. It is makes you code somewhat untestable. Maybe you should be something like:

// you might want to replace $_GET with $_SERVER['QUERY_STRING'] later
$router = new Router( $_GET['url'] );

// where 'default' is the name of fallback controller
$controller_class = $router->get_controller( 'default' );
$method_name = $router->get_action( 'index' );

$model_factory = new ModelFactory( new PDO( ... ) );
$controller = new {$controller_class}( $model_factory );
$controller->{$method_name}();

Additionally, you should look into php namespaces. There is no point in ending class with ...Controller just to know where the class will be located.

Ok ... back to the Model.

There is quite common misconception about models in web development community ( i blame RoR for this mess ). Model in MVC is not a class, but an application layer which contains multitude of instances. Most of the instances belong to one of two types of classes. With following responsibilities:

  • Domain Logic :

    Deals with all the computation, calculation and all the domain specific details. Objects in this group have no knowledge of where and how data is actually stored. They only manipulate the information.

  • Data Access

    Usually made of objects that fit DataMapper pattern (do not confuse with ORM of same name .. nothing in common). Responsible for storing data from Domain Objects and retrieving them. Might be in database.. might not. This is where your SQL queries would be.

In semi-real world situation () it might looks something like this (related to code abowe):

class SomeController
{
   // ... snip ...
   protected $model_factory = null;
   // ... snip ...

   public function __construct( ModelFactory $factory )
   {
       $this->model_factory = $factory;
   }
   // ... snip ...

   public function action_foobar()
   {
      $user = $this->model_factory->build_object( 'User' );
      $mapper = $this->model_factory->build_mapper( 'User' );

      $user->set_id(42);
      $mapper->fetch($user);

      if ( $user->hasWarning()  )
      {
          $user->set_status( 'locked' );
      }

      $mapper->store( $user );
   }

   // ... snip ...
}

As you see, there is no indication how the data was stored. It does not even matter if user account was new, or already existing.

Some materials you might find useful

Videos

Books:

I am busy writing a program in Visual Basic .NET and I have a few questions regarding best practices. I know it is a bit open ended, but just a few guidelines/ideas or even links would be appreciated.

Firstly, the code in the main form is getting a bit long (about 1000 lines). What is an acceptable number of lines of code for the main form or any other form for that matter? I have divided the program into classes as far is it makes logically sense to me. What are some good guidelines to what should be added together in a class? Should I add functions in classes as shared function rather than putting the code in the main form? Also, should I refrain from adding code in modules?

On a similar note, I am looking for information about how to design a large software project. I know the language pretty well now, but how does one actually plan how to create a large program or does that only come with experience?

Read Clean Code and about SOLID principles. This will be a great place to start.

I have a bunch of classes in a CUDA project that are mostly glorified structs and are dependent on each other by composition:

class A {
    public:
        typedef boost::shared_ptr<A> Ptr;
        A(uint n_elements) { ... // allocate element_indices };
        DeviceVector<int>::iterator get_element_indices();
    private:
        DeviceVector<int> element_indices;
}

class B {
    public:
        B(uint n_elements) { 
            ... // initialize members
        };
        A::Ptr get_a();
        DevicePointer<int>::iterator get_other_stuff();
    private:
        A::Ptr a;
        DeviceVector<int> other_stuff;
}

DeviceVector is just a wrapper around thrust::device_vectors and the ::iterator can be cast to a raw device pointer. This is needed, as custom kernels are called and require handles to device memory.

Now, I do care about encapsulation, but

  • raw pointers to the data have to be exposed, so the classes using A and B can run custom kernels on the GPU
  • a default constructor is not desired, device memory should be allocated automatically --> shared_ptr<T>
  • only very few methods on A and B are required

So, one could make life much simpler by simply using structs

struct A {
    void initialize(uint n_elements);
    DeviceVector<int> element_indices;
}

struct B {
    void initialize(uint n_elements);
    A a;
    DeviceVector<int> other_stuff;
}

I'm wondering whether I'm correct that in the sense of encapsulation this is practically equivalent. If so, is there anything that is wrong with the whole concept and might bite at some point?

It's a trade off.

Using value structs can be a beautifully simple way to group a bunch of data together. They can be very kludgy if you start tacking on a lot of helper routines and rely on them beyond their intended use. Be strict with yourself about when and how to use them and they are fine. Having zero methods on these objects is a good way to make this obvious to yourself.

You may have some set of classes that you use to solve a problem, I'll call it a module. Having value structs within the module are easy to reason about. Outside of the module you have to hope for good behavior. You don't have strict interfaces on them, so you have to hope the compiler will warn you about misuse.

Given that statement, I think they are more appropriate in anonymous or detail namespaces. If they end up in public interfaces, people tend to adding sugar to them. Delete the sugar or refactor it into a first class object with an interface.

I think they are more appropriate as const objects. The problem you fall into is that you are (trying to) maintain the invariance of this "object" everywhere that its used for its entire lifetime. If a different level of abstraction wants them with slight mutations, make a copy. The named parameter idiom is good for this.

Domain Driven Design gives thoughtful, thorough treatment on the subject. It characterizes it a more practical sense of how to understand and facilitate design.

Clean Code also discusses the topic, though from a different perspective. It is more of a morality book.

Both are awesome books and generally recommend outside of this topic.

I have a more or less large Perl script of ~ 1000 lines. The script accepts a few arguments and it runs straight forward. No modules, no functions. The script could be divided into three parts, initialization part, arguments parsing part and work part, but I don't know how to do that. Everything must be kept in a single file. Please, can anyone give me instructions/advice how to structure my Perl script?

Thanks.

If you can see logical parts of your script, you should definitely abstract them into functions. Having a single script of over 1000 lines, and not breaking it up into whatever abstraction units your language provides (functions, classes, etc.) is a very bad idea. Maintaining your script, i. e. adding features and fixing bugs, will be a nightmare.

I strongly suggest you read the book Clean Code by Robert C. Martin. It uses Java for examples, but the ideas are applicable to any language. The one that is most relevant here is "Make your functions small. Then make them smaller."

I have a project for a web-app.

  1. Most classes of this project must be compiled into .jar file and put to server into codebase/WEB-INF/lib dir. These classes are used by server only.

  2. But I have some classes which need to be used on the server and the client. These classes must be put directly to codebase/[package.class].

  3. All of these classes depend on each other and vice-versa.

End of story. Now I try to move my project from IDE build to Gradle. My project contains two modules which depend on each other. InteljID provide warning for me and compile this fine. But with Gradle it gets stuck. So, can I somehow split these classes in two logical groups, and have an easy way to build the structure described above?

I was trying to make multi-project build, several sourceSets but everywhere I got the same circular dependency errors.

You need to refactor your code. One way of doing this is to create a separate project for the server specific code, another project for the client project and a common project for code that needs to be shared. Next, you can let the server project and the client project depend on the common project. However, there should not be any dependencies between the server project and client project themselves.

Typically, you would like to keep the common project as small as possible. Ask yourself if a certain class is necessary in both projects? If not, it should not be part of the common package. Make sure to keep your dependencies between classes, packages and projects unidirectional. This may include quite a lot of refactoring since the code is tangled.

Recommended reading:

I have to code in APL. Since the code is going to be maintained for a long time, I am wondering if there are some papers/books which contain heuristics/tips/samples to help in designing clean and readable APL programs.

It is a different experience than coding in other programming language. Making a function, for example. Small will not help: such a function can contain one line of code, which is completely incomprehensible.

First, welcome to the wonderful world of APL.

Writing readable and maintainable APL code is not much different than writing readable and maintainable code in any language. Any good book on writing clean code is as applicable to APL as any other language, perhaps even more so. I recommend Clean Code by Robert C. Martin.

Consider the guideline in this book that all code in a function should be at the same level of abstraction. This applies to APL 100 times over. For example, if you have a function named DoThisBigTask it should have very few APL primitive symbols in it, and certainly no long complex one-liners. It should just be series of calls to other, lower level functions. If these higher-level functions are all well-named and well-defined, the general drift should be easily determined by someone who does not even know APL. The lowest level functions will be nothing but primitives and will be inscrutable to the non-APLer. Depending on how they are written they may even initially appear inscrutable to a seasoned APLer. However, these low level functions should be short, have no side effects, and can easily be re-written rather than modified if the maintaining programmer is unable to understand the original coding technique.

In general, keep your functions short, well-named, well-defined, and to the point. And keep the lines of code even shorter. It is much more important to have well-defined and well-documented functions than it is to have well-written or well document lines of code.

i just finished Coding my PHP application now the coding has become somewhat Huge and and the comments i am using is looking Ugly and Ineffective, as every single line of code i have commented with // , this is my first coding and i am totally unaware of the methodology to adopt to make my comments look nicer and cleaner for the future reference to me or anyone. i would appreciate if someone suggest me the pattern with example..

Here is the function i wrote with the ugly comments i used. which pattern would you use for commenting the code?

//function to check if the uploaded Image is valid
    function valid_image($image, $target, $url, $width, $height = 0) {
            //Check if the uploaded image is of type jpeg
            //if not then pop up a warning message and return false and redirect back
        if( $image["type"] !== "image/jpeg") {
            alert('File must be of type image/jpeg'); 
            redirect_url($url);           
            return false;
            }
            //Check the file Dimension of the Uploaded Image if it matches with the defined Value
             //Get the Dimensions of the image
            list($image_width, $image_height) = getimagesize($image['tmp_name']);
            //If the Parameter Height is empty then just check the image width and ignore the height rule
            //Print the appropriate message and return false and redirect back
        if( $height == '0') {
        if( $image_width !== $width) {
            alert("Incorrect File Dimension for  " . $image['name'] . " Please make sure it is $width in width");
            redirect_url($url);
            return false;
            }
            }
            //If the function has got all the parameter then check both the defined height and width 
            //Print the appropriate message and return false and redirect back
    else if($image_width !== $width || $image_height !== $height) {
            alert("Incorrect File Dimension for  " . $image['name'] . " Please make sure it is  $width X $height  ");
            redirect_url($url);
            return false;
            }
            return true;
            }

Thanks in Advance.

You'll want to code in such a way that comments are superfluous.

I would refactor this code to reduce the need for comments. I would create new methods, like isJpeg(), and I would remove the redirecting from the function and instead use something like redirectUnless(valid_image()).

A statement like the following requires no comments as anyone can understand what that does.

if ($image->isJpeg())

I'd further recommend reading Clean Code.

I know the difference between static type and other types but I am not sure which is to used where. Now I am using static types in all places to avoid object instantiation. Is it a good idea to use it that way ? Is there any particular disadvantage in using static type in all places ??

EDIT

What do you call this as static String staff ?

This is an excellent question. Usually you should not use static methods/variables unless you know for sure that it's a correct application for it. In object oriented programming (OOP), objects encapsulate data and behavior. Typically, *instance methods are used to manipulate the object's data.

Static methods/variables should only be used for functionality that is not associated with any particular object. A good example of a valid application for static is Math.random().

Some notes about instance and static methods/variables:

  • Instance variables have access to static and instance variables/methods, but static methods can only access other static variables/methods.
  • A static variable will always be the same across all instances of a class.

A good book to read that covers this topic is Clean Code by Robert Martin. Highly recommended.

*instance methods are the opposite of static methods. They are associated with a class instance, instead of the class itself.


Addressing your edit, assuming that that's a variable, you'd access it like this:

MyClass.staff = "bob, george, and linda";
System.out.println(MyClass.staff);

Edit: here's a post I made on another forum a while back, with some good answers. It's a PHP forum, but the concepts still apply.

http://forums.devnetwork.net/viewtopic.php?f=1&t=127667

I'm reading a book called Clean Code -A Handbook of Agile Software Craftsmanship written by Robert C. Martin and in his book he gives a lot of useful tips how to write good Java code.

And one of those tips is:

Blocks within if statements, else statements, for statements, and so on should be one line long. Probably that line should be a function call. Not only does this keep the enclosing function small, but it also adds documentary value because the function called within the block can have a nicely descriptive name

For me that was very strange hint, because from this code:

public Map<String, List<Issue>> mapComponentToIssueList(List<Issue> issues) {
    Map<String, List<Issue>> map = new HashMap<String, List<Issue>>();

    for (Issue issue : issues) {
        String componentName = issue.getComponents().iterator().next().getString("name");
        if (map.containsKey(componentName)) {
            map.get(componentName).add(issue);
        } else {
            List<Issue> list = new ArrayList<Issue>();
            list.add(issue);
            map.put(componentName, list);
        }
    }
    return map;

}

Using this principle I've got this:

public Map<String, List<Issue>> mapComponentToIssueList(List<Issue> issues) {
    Map<String, List<Issue>> componentNameIssueListMap = new HashMap<String, List<Issue>>();
    for (Issue issue : issues) {
        populateMapWithComponenNamesAndIssueLists(componentNameIssueListMap, issue);
    }
    return componentNameIssueListMap;
}

private void populateMapWithComponenNamesAndIssueLists(Map<String, List<Issue>> componentNameIssueListMap, Issue issue) {
    String componentName = getFirstComponentName(issue);
    if (componentNameIssueListMap.containsKey(componentName)) {
        componentNameIssueListMap.get(componentName).add(issue);
    } else {
        putIssueListWithNewKeyToMap(componentNameIssueListMap, issue, componentName);
    }
}

private void putIssueListWithNewKeyToMap(Map<String, List<Issue>> componentNameIssueListMap, Issue issue, String componentName) {
    List<Issue> list = new ArrayList<Issue>();
    list.add(issue);
    componentNameIssueListMap.put(componentName, list);
}

private String getFirstComponentName(Issue issue) {
    return issue.getComponents().iterator().next().getString("name");
}

So basically the code has doubled in size.Was it useful? - Maybe.

What code in my example is so called clean? What am I doing wrong? What do you guys think about this?

Frankly, I think the tip is silly because it's so extreme.

Personally, if I were to do anything to your function, I'd change it like so:

public Map<String, List<Issue>> mapComponentToIssueList(List<Issue> issues) {
    Map<String, List<Issue>> map = new HashMap<String, List<Issue>>();

    for (Issue issue : issues) {
        String componentName = issue.getComponents().iterator().next().getString("name");
        List<Issue> list = map.get(componentName);
        if (list == null) {
            list = new ArrayList<Issue>();
            map.put(componentName, list);
        }
        list.add(issue);
    }
    return map;
}

The benefits are:

  1. You only do the map lookup once instead of twice.
  2. The list.add() call is not duplicated in two places.

Now if you wanted to factor something out, the following would be a good candidate:

        List<Issue> list = map.get(componentName);
        if (list == null) {
            list = new ArrayList<Issue>();
            map.put(componentName, list);
        }

I would definitely do it if the above appeared in more than one place. Otherwise, probably not (at least not initially).

In Jeffrey Richter's "CLR via C#" (the .net 2.0 edtion page, 353) he says that as a self-discipline, he never makes anonymous functions longer than 3 lines of code in length. He cites mostly readability / understandability as his reasons. This suites me fine, because I already had a self-discipline of using no more than 5 lines for an anonymous method.

But how does that "coding standard" advice stack against lambda's? At face value, I'd treat them the same - keeping a lambda equally as short. But how do others feel about this? In particular, when lambda's are being used where (arguably) they shine brightest - when used in LINQ statements - is there genuine cause to abandon that self-discipline / coding standard?

I don't know if having a guideline for short lambda's and delegates is really useful. However, have a guideline for having short functions. The methods I write are on average 6 or 7 lines long. Functions should hardly ever be 20 lines long. You should create the most readable code and if you follow Robert Martin's or Steve McConnell's advice, they tell you to keep functions short and also keep the inner part of loops as short of possible, favorably just a single method call.

So you shouldn't write a for loop as follows:

for (int i = 0; i < 100; i++)
{
    // Potentially significant amounts of code
}

but simply with a single method call inside the loop:

for (int i = 0; i < 100; i++)
{
    WellDescribedOperationOnElementI(i);
}

With this in mind, while I in general agree with Jon Skeet’s answer, I don't see any reason why you shouldn't want his example to be written as:

Parallel.For(0, 100, i =>
{
    WellDescribedPartOfHeavyCalculation(i);
});

or

Parallel.For(0, 100, i => WellDescribedPartOfHeavyCalculation(i));

or even:

Parallel.For(0, 100, WellDescribedPartOfHeavyCalculation);

Always go for the most readable code, and many times this means: short anonymous methods, and short lambda's, but most of all short -but well described- methods.

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

eg.

Option 1: Outside the Loop

List list = new ArrayList();
int value;

//populate list
for(int i = 0 ; i < list.size(); i++) {
  value = list.get(i);
  System.out.println(“value is ”+ value);
}

Option 2: Inside the Loop

List list = new ArrayList();

//populate list
for(int i = 0; i < list.size(); i++) {
  int value = list.get(i);
  System.out.println(“value is ”+ value);
}

In Clean Code, Robert C. Martin advises Java coders to declare variables as close as possible to where they are to be used. Variables should not have greater scope than necessary. Having the declaration of a variable close to where it's used helps give the reader type and initialization information. Don't concern yourself too much with performance because the JVM is pretty good at optimizing these things. Instead focus on readability.

BTW: If you're using Java 5 or greater, you can significantly trim up your code example using the following new-for-Java-5 features:

  • foreach construct
  • generics
  • autoboxing

I've refactored your example to use the aforementioned new features.

List<Integer> list = new ArrayList<Integer>();

// populate list

for (int value : list) {
    System.out.println("value is " + value);
}

Is one option generally faster than the other?

Option A: $var = $_GET['param']; and then referencing $var through the script.
Option B: Referencing $_GET['param'] in each occurrence through the script.

Thanks!

Agreed with those that say you're worrying about the wrong level of optimization. (Though, if you really want to obsess over this sort of thing,check out http://www.phpbench.com/)

Your first level of optimization should be optimizing the readability and maintainability of the code. Human clock cycles are far more valuable and expensive (generally speaking) than computer clock cycles. As an added bonus, you'll be very pleasantly surprised how often optimizing for human clock cycles will also make the code remarkably faster.

I strongly recommend Clean Code by Robert C. Martin for an excellent guide to coding style.

Let me set the scene.

The Scene

We're a web development company, and so we work within a highly distributed environment. DB Servers, Services, Web Services, Front-end, Back-end, etc etc. I'm not sure if that's relevant, but there it is.

Essentially though, at it's most basic, we develop custom web solutions, and maintain one large CMS application, which we use to leverage 80% of our projects.

The Problem

The CMS application works, kinda, but it has to be customized and changed almost all the time for each project. Every time I go in it, or fix the same problem over and over again, I want to cry.

It just could be so much better, and in it's current form, it's very inflexible, and rigid. For example:

  • There's repeated code all over the place
  • Global business logic is spread out all over different layers, multiple times, making it a dog to change, anytime anything has to be modified
  • there's loads of god classes, and the structure doesn't make any sense
  • etc etc.

Not only is this ugly, and annoying, but it makes it prone to bugs, and hard to extend. For example, it would be great if the CMS worked at an API level, but because there's business code all over the UI, it cannot.

The Question

I would love to discuss with my peers solutions for these problems, and fix/rewrite a lot of the issues in the application in a collaborative effort, because I believe it would have a lot of long-term benefits.

For example, it would make each individual project take less time, because there would less bugs to fix. It would make customizing easier, and it would make extending and building a better application simpler.

However, I realize this would be a relatively massive undertaking, and thus would cost a lot of money.

The alternative, which my seniors dictate, is to keep hacking the application each time with quick, non reusable "fixes", which I hate, but it does make it "work", doesn't take THAT long, and so perhaps makes more economic sense?

Who's right? Am I just an idealist fool?

The question is, should I approach my seniors and make a case for it, or not?

UPDATE:

Hey guys, I know my question gets a bit specific towards the end, but I'm really enjoying all your general feedback, and the experiences you've had, and how you dealt with it.

Thanks again, keep 'em coming!

First learn to write code which does not rot when the project is maintained, but instead gets better as time goes on (TDD/BDD, Clean Code, Boy Scout Rule, DRY, YAGNI, SOLID etc.). Learning is easiest done in small greenfield projects.

Then when you have the skills, apply them to the legacy projects and improve them gradually (Working Effectively with Legacy Code, short version also in PDF). Gradual improvement is easier to sell to the management than a big bang rewrite (not that a rewrite would even help in the long run, unless you know how to write code which does not rot, and in that case you would anyways be able to improve the legacy code without a rewrite).

So this is regarding an interview question I was recently asked. The interviewer started on this by asking me how we create our custom Exceptions. On answering that, he asked me how I'd create a RunTimeExceptions. I said we'd create them in the same way as we would create the checked Exceptions. Just our custom exception would extend from the RunTimeException class. Then he asked in what scenarios would you create your own RunTimeException. Now I couldn't think of a good answer to that. In none of my projects, we created custom RunTimeExceptions.

I also think that we should never create RunTimeExceptions. JVM can fail only in a finite number of ways and it handles them well. While writing an application we can't predict what runtime exceptions can occur and hence we shouldn't need to handle them. And if we can predict those conditions, they aren't RunTimeExceptions then. Since we neither need new runtime exceptions, nor need a handling of runtimeexceptions, why would we ever need to create a custom RunTimeException. Everything that we can pre-think of as a possible failure condition should be handled at compile time and it would be a checked exception. Right? Only the things that cannot be handled at compile time and the ones that depend on run time things go into the category of RunTimeExceptions.

Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException. How do we do that mapping. It doesn't seem possible to me.

Am I missing something/ many things here? Kindly advice.

Thanks, Chan.

Checked Exception vs Unchecked Exception is a long time debate among Java developers. I'm not be here to ignite the fire, but only want to share with you how I use it in our work.

For example, another service call my server for customer information. The input is customerID, and I will return a customer object

// Web Service interface
public CustomerInfo getCustomerInformation(int customerId, int securityToken) {
   check(securityToken);
   Customer customer = merchantService.getCustomer(customerId);
   return customer.getInfo();
}

// MerchantService
public Customer getCustomer(int customerId) {
   return customerService.getCustomer(customerId);
}

What will happen if the system can't find a particular customer? Of course it will throw an exception or return null. But returning null is bad, since it will make you check null everytime calling from a service. So I go with throwing exception:

// Customer service
public Customer getCustomer(id) {
   Customer customer = getCustomerFromDB();
   if (customer == null) throw CustomerNotExistedException();
   return customer;
}

Now the question is whether CustomerNotExistedException is a Exception or a RuntimeException. If it's a checked exception, you will need to catch and process it at the function that calls getCustomer. That means you must catch it at MerchantService. However, all you want is to produce a 404 error at WebService level, so that catching it at MerchantService won't do anything more than throwing the exception again. It pollutes the code.

In the general case, I often use RuntimeException to let some exception "bubble up" to the level in which they can be processed.

For your reference, I would recommend the book Clean code from Robert C. Martin. It explains quite well how we should use exception to handle errors in Java.

What do you do when your manager wants you to implement something in a quick and dirty way and you just know it's going to backfire?

My manager wants me to develop a web app for a client and to do it as quickly as possible. This is the first web app we're building for this client, and I think it's important that we do it right so that we will be able to build upon it when they inevitably ask us to enhance it or create a new one.

I'd like to spend some time setting up a framework (even if it's just something simple like Stripes), and configuring tomcat to use DBCP. I also think we should be using css templates, and giving at least a minimum amount of thought to the presentation and design of the app as, in my opinion, nothing looks quite as unprofessional as a poorly designed web page (unless it's an email with really bad grammar).

The problem is not so much that we're under pressure to get this done, but more that my manager does not feel he can justify billing extra hours for something he himself does not consider a necessity. His "just get it done ASAP" approach has already backfired a few times - once, for example, he told me not to design the code to handle a certain error situation as it was very unlikely to occur, and then when it did occur it was a big mess (that I had to clean up).

So what do I do? Do I really do it "quick and dirty"? Do I decide that the quickest way is to do it right and deal with the fallout if it takes me longer than he had hoped? Part of the issue here is that while I have done web development in the past, it's always been within an existing framework, so setting up a framework from scratch involves a learning curve for me.

If it's just a demo for a client I think a quick-and-dirty solution is sufficient, but ultimately it is you're job as a developer to protest if you think it's going to backfire. Uncle Bob in Clean Code drives home the point well:

"What if you were a doctor and had a patient who demanded that you stopped all the silly hand-washing in preparation for surgery because it was taking too much time? Clearly the patient is the boss, and yet the doctor should absolutely refuse to comply. Why? Because the doctor knows more than the patient about the risks of the disease and infection. It would be unprofessional (never mind criminal) for the doctor to comply with the patient.

So too it is unprofessional for programmers to bend to the will of managers who don't understand the risks of making messes."

What tips/suggestions do you have for writing more understandable code?

I've been somewhat frustrated by the lack of structure and bad format of some code I've been maintaining lately and would like to propose a series of guidelines for writing more understandable code.

Any suggestion might help, no matter the language.

Regards.

The key to writing maintainable code is to follow some fundamental code design principles:

  1. Single Responsibility Principle - SRP - One class must implement one responsibility.
  2. DRY - almost reciprocal to SRP - Don't repeat Yourself - in other words don't let the same responsibility be implemented by multiple classes (for it would result in repetition of the same code)
  3. Make vertical slices of the application and call each slice a module. Come up with a modular structure with clear cut dependencies between modules. Publish a module structure for the project and enforce that the team complies to it. Obviously no cyclical dependencies. Use a tool like maven or apache ivy for dependency management during builds.
  4. Have an approach to implement non functional requirements as horizontal requirements using strategies such as AOP, decorators etc.

With these things in place, most of the code would become maintainable. Each of the points above is itself pretty involved. I absolutely love this book.

Look at blogs etc where these things are discussed. All the best

I liked these books:

You should also read code. If the code is hard to read, ask yourself what exactly the author did or didn't do that makes it hard to understand, and more importantly, how you can use what you've learned to write better code yourself.

Writing clean, elegant code is what makes coding a pleasure for me. I'm always looking for more ways to do so. Here are some of my strategies/tactics:

  • Keep large code blocks in smaller chunks of routines/methods/classes

  • Be sure every routine has one point of exit. Exit loops with logic at the top of the loop, not with breaks or some type of "exit loop" keyword.

  • Avoid globals

  • If you just performed a copy/paste with your code, it is time to create a routine/class/library.

...and one I've been toying with lately:

  • Try to replace if/branching/select cases with different method signatures (polymorphism) Clean Code Talks on YouTube

first of all I'm using java, even though it could be a question for any language

say I have a complicated system, now sometimes I end up building objects (setting all the parameters), then passing it over to a "target layer"(manager), which opens the object (getting the parameters).

if I were to pass all the parameters in one function, it would be considered poor design, because there's suppose to be a small amount of parameters per function

this seems like a waste, and in the past I also decided to set the parameters straight to the "target layer"

is there a design pattern that deals with this issue? or something that books or experts in the subject recommend?

Since you were asking about book references, here is one from Clean Code, Chapter 3: Functions:

When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own. [...]

Reducing the number of arguments by creating objects out of them may seem like cheating, but it’s not. When groups of variables are passed together, [...] they are likely part of a concept that deserves a name of its own.

So I guess it's ok to group a lot of method arguments into classes, as long as these classes represent some coherent concepts.

Personally if I do something like this, I like the wrapper class to be immutable and created by a dedicated builder. Which increases the number of additional classes twofold (wrapper and the builder), but enables the treatment of such a class as one atomic argument.

I am recieving warning about my file by StyleCop.

  • Warning 1 CR0005: The file is very long at 508 lines. Please consider refactoring to make it 500 or fewer lines.

  • Warning 2 CR0002: Method is too long. It is 58 lines long. Consider refactoring to make it 50 or fewer lines.

How are you guys making changes to your codes? What are the best practices for this? I have no idea to divide my codes to smaller ones - being afraid of making my codes become so-complex.

So, please help ^_^ !

Nam.

Others have mentioned refactoring, and also focusing on breaking the class down to do just 1x responsibility (part of the S.O.L.I.D. rules for OOP). However; if your class is still 500x lines, and performing one responsibility, then you're not in too terrible a position.

If your code-file contains XML documentation and white-spaces, then 500x lines is only slightly large (and that's dependent on what it does). Many of my "simple" classes end up around 350 lines once completed. Smaller is better, but concise is really what you want.

Another good book for understanding how your code should look is Robert C. Martin's Clean Code. It lays down many good rules in designing well thought-out classes and methods.

I come from a C#.net background and whenever I had a string I was declaring it as String.Empty Now I am looking at a Java code from a co-worker and he has declared his strings in a method like this:

String myStr = null;

I don't like it, and even worse, he is assigning values to these strings in an "IF" block where it may or may not even qualify, and then at the end of the method he is calling a myStr.length() on them.

So my question is what is a preferred way in Java? do you think is it better to define them as String.Empty OR leave them as null and do a null check just before calling .length() on them?

In general, using null values is a bad idea, especially if they are returned from a method or passed to another method. Using the Null Object pattern is better, and in a string's case the Null Object is an empty string. By consistently avoiding nulls, the probability of getting a NullPointerException gets smaller and the code becomes more readable (this is discussed at length in Clean Code chapter 7, pages 110-112).

In Java String s = "" does not allocate any memory, because the JVM will have interned the string literal, so there isn't even a performance difference (and even if there were, it would be a premature optimization).

I got a question regarding to these two possibilities of setting a value:

Let's say I got a string of a class which I want to change. I am using this:

void setfunc(std::string& st) { this->str = st; }

And another function which is able to do the exact same, but with a string reference instead of a void for setting a value:

std::string& reffunc() { return this->str; }

now if I am going to set a value I can use:

std::string text("mytext");
setfunc(text);
//or
reffunc() = text;

Now my question is if it is considered bad at using the second form of setting the value. There is no performance difference.

The way you used the reffunc() function is considered bad coding. But (as mentioned in the comments), generally speaking, returning references is not bad coding.

Here's why reffunc() = text; is considered bad coding:

People usually do not expect function calls on the left hand of an assignment, but on the right side. The natural expectation when seeing a function call is that it computes and returns a value (or rvalue, which is expected to be on the right hand side of assignment) and not a reference (or lvalue, which is expected to be on the left hand side of assignment).

So by putting a function call on the left hand side of the assignment, you are making your code more complicated, and therefore, less readable. Keeping in mind that you do not have any other motivations for it (as you say, performance is the same, and it usually is in these situations), good coding recommends that you use a "set" function.

Read the great book "Clean Code" for more issues on clean coding.

As for returning references in functions, which is the title of your question, it is not always bad coding and is sometimes required for having cleaner and briefer code. Specifically many operator overloading features in c++ work properly if you return a reference (see operator[] in std::vector and the assignment operator which usually help the code become more readable and less complex. See the comments).

I have recently been learning more about design patterns and thought I'd take a crack at it. I'm not sure if this is the correct way to use the factory pattern and was wondering if someone could provide me with feedback?

I basically have a set of calendar items that are similar. Meals, workouts and measurements. They all have a date and a name and can print details. but other than that they have a few items they each need differently.

    public enum AppointmentType
{
    Workout,
    Meal,
    Measurement
}

public abstract class Appointment
{
    public string Name { get; set; }
    public DateTime DateStarted { get; set; }

    public virtual string PrintDetails()
    {
        return string.Format("Type: {0}\nName: {1}\nDate: {2}",this.GetType().ToString(), Name, DateStarted.ToShortDateString());
    }
}

public class Workout : Appointment
{
    public List<string> Exercises { get; set; }

    public Workout()
    {
        Exercises = new List<string>();
    }

    public override string PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = "\nToday I will be doing the following:\n";

        foreach (string exercise in Exercises)
        {
            addedInfo += string.Format("{0}\n", exercise);
        }

        return startInfo + addedInfo;
    }
}

public class Meal : Appointment
{
    public List<string> FoodItems { get; set; }

    public Meal()
    {
        FoodItems = new List<string>();
    }

    public override string PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = "\nToday I will be eating the following:\n";

        foreach (string foodItem in FoodItems)
        {
            addedInfo += string.Format("{0}\n", foodItem);
        }

        return startInfo + addedInfo;
    }
}

public class Measurement : Appointment
{
    public string Height { get; set; }
    public string Weight { get; set; }

    public override string PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = string.Format("\nI am {0} feet tall and I weight {1} pounds!\n", Height, Weight);
        return startInfo + addedInfo;
    }
}

public interface IAppointmentFactory
{
    Appointment CreateAppointment(AppointmentType appointmentType);
}

public class AppointmentFactory : IAppointmentFactory
{
    public Appointment CreateAppointment(AppointmentType appointmentType)
    {
        switch (appointmentType)
        {
            case AppointmentType.Workout:
                return new Workout();
            case AppointmentType.Meal:
                return new Meal();
            case AppointmentType.Measurement:
                return new Measurement();
            default:
                return new Workout();
        }
    }
}

and here is a program using the library:

  class Program
{
    public static List<Appointment> myAppointments;
    public static AppointmentFactory factory;
    public static Appointment myAppointment;

    static void Main(string[] args)
    {
        myAppointments = new List<Appointment>();
        factory = new AppointmentFactory();
        StartLoop();
    }

    private static void StartLoop()
    {
        Console.WriteLine(string.Format("\nWelcome to Appointment App: You have {0} appointment(s)!", myAppointments.Count()));
        Console.WriteLine("0 = Exit");
        Console.WriteLine("1 = New Workout");
        Console.WriteLine("2 = New Meal");
        Console.WriteLine("3 = New Measurement");
        Console.WriteLine("P = Print Schedule\n");

        switch (Console.ReadLine().ToUpper())
        {
            case "0":
                return;
            case "1":
                CreateNewAppointment(AppointmentType.Workout);
                AddExercises();
                break;
            case "2":
                CreateNewAppointment(AppointmentType.Meal);
                AddFoodItems();
                break;
            case "3":
                CreateNewAppointment(AppointmentType.Measurement);
                GetMeasurements();
                break;
            case "P":
                PrintSchedule();
                break;
            default:
                return;
        }

        StartLoop();
    }

    private static void GetMeasurements()
    {
        Console.WriteLine("How tall are you?");
        ((Measurement)myAppointment).Height = Console.ReadLine();
        Console.WriteLine("What is your weight?");
        ((Measurement)myAppointment).Weight = Console.ReadLine();
    }

    private static void AddFoodItems()
    {
        Console.WriteLine("How many food items do you want to add?");
        string exerciseCount = Console.ReadLine();

        for (int i = 0; i < Convert.ToInt32(exerciseCount); i++)
        {
            Console.WriteLine(string.Format("Food {0}:", (i + 1)));
            ((Meal)myAppointment).FoodItems.Add(Console.ReadLine());
        }
    }

    private static void AddExercises()
    {
        Console.WriteLine("How many exercises do you want to add?");
        string exerciseCount = Console.ReadLine();

        for (int i = 0; i < Convert.ToInt32(exerciseCount); i++)
        {
            Console.WriteLine(string.Format("Exercise {0}:", (i + 1)));
            ((Workout)myAppointment).Exercises.Add(Console.ReadLine());
        }
    }

    private static void PrintSchedule()
    {
        foreach (Appointment appointment in myAppointments)
        {
            Console.WriteLine(appointment.PrintDetails());
        }
    }

    public static void CreateNewAppointment(AppointmentType appointmentType)
    {
        myAppointment = factory.CreateAppointment(appointmentType);

        Console.WriteLine("Name:");
        myAppointment.Name = Console.ReadLine();
        Console.WriteLine("Start Date:");
        myAppointment.Name = Console.ReadLine();

        myAppointments.Add(myAppointment);
    }
}

Thanks!!

-ajax

Here's what I would change it to:

public enum AppointmentType
{
    Workout,
    Meal,
    Measurement
}

public abstract class Appointment
{
    public string Name { get; set; }
    public DateTime DateStarted { get; set; }

    public abstract void PrintDetails();
    public abstract void RequestInputFromUser();
}

public class Workout : Appointment
{
    private List<string> Exercises { get; set; }

    public Workout()
    {
        Exercises = new List<string>();
    }

    public override void PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = "\nToday I will be doing the following:\n";

        foreach (string exercise in Exercises)
        {
            addedInfo += string.Format("{0}\n", exercise);
        }

        Console.WriteLine(StartInfo + addedInfo);
    }

    public override void RequestInputFromUser()
    {
        Console.WriteLine("How many exercises do you want to add?");
        string exerciseCount = Console.ReadLine();

        for (int i = 0; i < Convert.ToInt32(exerciseCount); i++)
        {
            Console.WriteLine(string.Format("Exercise {0}:", (i + 1)));
            Exercises.Add(Console.ReadLine());
        }
    }
}

public class Meal : Appointment
{
    private List<string> FoodItems { get; set; }

    public Meal()
    {
        FoodItems = new List<string>();
    }

    public override void PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = "\nToday I will be eating the following:\n";

        foreach (string foodItem in FoodItems)
        {
            addedInfo += string.Format("{0}\n", foodItem);
        }

        Console.WriteLine(startInfo + addedInfo);
    }

    public override void RequestInputFromUser()
    {
        Console.WriteLine("How many food items do you want to add?");
        string exerciseCount = Console.ReadLine();

        for (int i = 0; i < Convert.ToInt32(exerciseCount); i++)
        {
            Console.WriteLine(string.Format("Food {0}:", (i + 1)));
            FoodItems.Add(Console.ReadLine());
        }
    }
}

public class Measurement : Appointment
{
    private string Height { get; set; }
    private string Weight { get; set; }

    public override void PrintDetails()
    {
        string startInfo = base.PrintDetails();
        string addedInfo = string.Format("\nI am {0} feet tall and I weight {1} pounds!\n", Height, Weight);
        Console.WriteLine(startInfo + addedInfo);
    }

    public override void RequestInputFromUser()
    {
        Console.WriteLine("How tall are you?");
        Height = Console.ReadLine();
        Console.WriteLine("What is your weight?");
        Weight = Console.ReadLine();
    }
}

public interface IAppointmentFactory
{
    Appointment CreateAppointment(AppointmentType appointmentType);
}

public class AppointmentFactory : IAppointmentFactory
{
    public Appointment CreateAppointment(AppointmentType appointmentType)
    {
        Appointment apt;

        switch (appointmentType)
        {
            case AppointmentType.Workout:
                apt = new Workout();
            case AppointmentType.Meal:
                apt = new Meal();
            case AppointmentType.Measurement:
                apt = new Measurement();
            default:
                apt = new Workout();
        }

        Console.WriteLine("Name:");
        apt.Name = Console.ReadLine();
        Console.WriteLine("Start Date:");
        apt.Name = Console.ReadLine();    // Logic error on this line.
                                          // Change it to do what you mean.

        apt.RequestInputFromUser();

        return apt;
    }
}

with the code using it as follows:

class Program
{
    public static List<Appointment> myAppointments;
    public static AppointmentFactory factory;
    public static Appointment myAppointment;

    static void Main(string[] args)
    {
        myAppointments = new List<Appointment>();
        factory = new AppointmentFactory();
        StartLoop(factory);
    }

    private static void StartLoop(IAppointmentFactory factory)
    {
        bool exit = false;

        while(!exit)
        {

            Console.WriteLine(string.Format("\nWelcome to Appointment App: You have {0} appointment(s)!", myAppointments.Count()));
            Console.WriteLine("0 = Exit");
            Console.WriteLine("1 = New Workout");
            Console.WriteLine("2 = New Meal");
            Console.WriteLine("3 = New Measurement");
            Console.WriteLine("P = Print Schedule\n");

            switch (Console.ReadLine().ToUpper())
            {
                case "0":
                    exit = true;
                    break;
                case "1":
                    myAppointments.Add( factory.CreateAppointment( AppointmentType.Workout ) );
                    break;
                case "2":
                    myAppointments.Add( factory.CreateAppointment( AppointmentType.Meal ) );
                    break;
                case "3":
                    myAppointments.Add( factory.CreateAppointment( AppointmentType.Measurement ) );
                    break;
                case "P":
                    PrintSchedule();
                    break;
                default:
                    exit = true;
            }

        }

    }

    private static void PrintSchedule()
    {
        foreach (Appointment appointment in myAppointments)
        {
            appointment.PrintDetails();
        }
    }

}

A couple things to notice:

  • All properties in the lower classes are private (a good thing)
  • There is no type casting (another good thing)
  • It is easy to add another Appointment type (another good thing)

There are still things that can change. The base class having public properties is still a bad thing. But this is a large improvement.

I also removed the recursive call to StartLoop(). You don't want to grow the stack when all you need is a loop.

EDIT: Made some more changes to the Factory class.

In response to comments:

  • To remove the dependency on the Console, create an interface that represents what you want to do with IO. Create classes that implement this interface and send an instance to the Appointment class. From there, have everything use the instance of the IO engine. To change the platform, change the IO-implementing class that is sent to the Appointment class
  • Public properties are bad for the same reason that public variables are bad. A class should hide its implementation, and public properties expose the implementation. For more detail, I suggest Clean Code. It describes it much better than I can.

Overall, not bad :)

I just finished creating my first major application in C#/Silverlight. In the end the total line count came out to over 12,000 lines of code. Considering this was a rewrite of a php/javascript application I created 2 years that was over 28,000 lines I am actually quite proud of my accomplishment.

After reading many questions and answers here on stackoverflow and other sites online, I followed many posters advice: I created classes, procedures, and such for things that I would have a year ago copied and pasted; I created logic charts to figure out complex functions; making sure there are no crazy hidden characters (used tabs instead of spaces); and a few others things; place comments where necessary (I have lots of comments).

My application consists of 4 tiles laid out horizontally that have user controls loaded into each slice. You can have between one and four slices loaded at anytime. If you have once slice loaded, the slice takes up the entire artboard...if you have 2 loaded, each take up half, 3 a third, 4 a quarter.

Each one of these slices represent (for the sake of this example) a light control. Each slice has 3 slider controls in it. Now when I coded the functionality of the sliders, I used a switch/case statement inside of a public function that would run the command on the specified slice/slider. This made for some duplicate code but I saw no way around it as each slice was named differently. So I would do slice1.my.commands(); slice2.my.commands(); etc.

My question to you is how do I clean up my code even futher? (Sadly I cannot post any of my code). Is there any way to take this repetion out of my code?

Writing less code shouldn't be your goal. In the end it's all about TCO (Total cost of ownership).

While owning less code can improve the TCO, there is one factor that has a much greater impact for TCO: maintainability. You should write the most maintainable code. Start by reading Robert Martin's Clean Code.

Update:

Also you say “I have lots of comments”. This is a point where you might improve your code. As you will learn from Martin’s book, good code hardly needs any comments. Martin says that “comments are lies” and “should be reserved for technical notes about the code and design.”.

Update 2:

While I'm add it, here are my favorite quotes from Robert Martin's book:

  • "a class or module should have one, and only one, reason to change [Single Responsibility Principle]" [page 138]
  • "More than three [method arguments] is very questionable and should be avoided with prejudice." [page 288]
  • "The First rule of functions is that they should be small. The second rule of functions is that they should be smaller than that." [page 34]
  • "Functions should hardly ever be 20 lines long" [page 34]
  • "The statements in a function should all be written at the same level of abstraction" [page 304]
  • "Comments should be reserved for technical notes about the code and design." [page 286]

In the book Core Java Ⅰ, it says ...

protected keywords should be carefully used. If you set a class with a protected field, than, if you want to change it, you must notify all programmers who use this class.

I can not understand. If Son extends Father, and Father has changed, Son has not been affected. Is it right?

I can not understand. If Son extends Father, and Father has changed, Son has not been affected. is it right?

Short answer is: No, for the general case!

Suppose you have the two classes you describe in version 1 of your source code:

Version 1

class Father { protected int asdf; }
class Son extends Father { int qwer = 2 * asdf; }

Now lets change the protected field asdf of the Father

Version 2

class Father { protected int fdsa; }
class Son extends Father { int qwer = 2 * asdf; } // compile error

Now you MUST change the Son as well, so it definitely affects the sub class.

Libraries

Let's think about a library, we assume you are using a lot. Let's say you have derived 20 classes from the core library classes. With the next update of the library your 20 classes might gonna have to change as well. This is because protected breaks encapsulation.

Further Reading

There are several good resources depicting all the nifty details about this issue, a nice summation can be found here on programmers SE network. I try to summarize it even more now.

Using protected tends to;

  1. lead to YAGNI issues.
  2. lead to LSP issues.
  3. violate OCP.
  4. design where inheritance is favored over composition.
  5. lead to more violation of the SRP.

Another good reference is Clean Code from Robert C. Martin (alias Uncle Bob).

Is it bad to have a lot of methods referring to each other, like the following example?

public void MainMethod()
{
   GetProducts();  
}

public void GetProducts()
{
   var _products = new Products();
   var productlist = _products.GetProductList;
   GetExcelFile(productlist);
}

public void GetExcelFile(List<product> productlist)
{
   var _getExcelFile = new GetExcelFile();
   var excelfile = _getExcelFile.GetExcelFileFromProductList(productlist);

   //create excel file and so on...
}

So I am creating a new method for every little action. It would be just as easy to call GetProducts from the MainMethod and do all actions in that method, but I think that isn't the way to create re-usable code.

The following tells me that there should be no more than 7 statements in a method:

Only 7 statements in a method

So the advantages of using methods with a minimal amount of code:

  • Code is re-usable
  • Every task can get his own method

The disadvantages of using methods with a minimal amount of code:

  • It's like spaghetti code
  • You get: refer to refer and so on

My question:

Should my methods be bigger, or should I keep creating small methods, that do little and refer to a lot of other methods?

The guideline is right. Methods should be small and you are doing the right thing be giving not only each operation its own method, but a well defined name. If those methods have a clear name, one responsibility and a clear intention (and don't forget to separate commands from queries), your code will not be spagetti. On top of that, try to order methods like a news article: most important methods on top of the file, methods with the most detail on the bottom. This way anyone else can start reading at the top and stop reading when they're bored (or have enough information).

I can advice you to get a copy of Robert Martin's Clean Code. There's no one in the industry who describes this more clearly than he does.

I've been coding for a while, but still consider myself a beginner. I use very simplistic ADO.NET classes with inbuilt SQL statements. I'd like to hear from the community about what I'm doing wrong and how I can improve, and what the suggested next steps are to take my coding into current standards.

I'm really interested in trying EF, although I can't seem to find a tutorial that fits in with the way I do my BLL and DAL classes, so would appreciate a pointer in the right direction.

Basically if I have a Gift, I would create a Gift class (BLL\Gift.cs):

using MyProject.DataAccessLayer;

namespace MyProject.BusinessLogicLayer
{
public class Gift
{

    public int GiftID { get; set; }
    public string GiftName { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }

    public static Gift GetGiftByID(int GiftID)
    {
        GiftDAL dataAccessLayer = new GiftDAL();
        return dataAccessLayer.GiftsSelectByID(GiftID);
    }

    public void DeleteGift(Gift myGift)
    {
        GiftDAL dataAccessLayer = new GiftDAL();
        dataAccessLayer.DeleteGift(myGift);
    }

    public bool UpdateGift(Gift myGift)
    {
        GiftDAL dataAccessLayer = new GiftDAL();
        return dataAccessLayer.UpdateGift(myGift);
    }

    public int InsertGift(string GiftName, string Description, decimal Price)
    {
        Gift myGift = new Gift();
        myGift.GiftName = GiftName;
        myGift.Description = Description;
        myGift.Price = Price;

        GiftDAL dataAccessLayer = new GiftDAL();
        return dataAccessLayer.InsertGift(myGift);
    }
}
}

I then have a DAL class which holds my connection string (DAL\sqlDAL.css):

namespace MyProject.DataAccessLayer
{
public class SqlDataAccessLayer
{
    public readonly string _connectionString = string.Empty;

    public SqlDataAccessLayer()
    {
        _connectionString = WebConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
        if (string.IsNullOrEmpty(_connectionString))
        {
            throw new Exception("No database connection String found");
        }
    }
}
}

and then a DAL class (DAL\giftDAL.cs) where I've shown a couple of the methods (Update and Delete):

using MyProject.BusinessLogicLayer;

namespace MyProject.DataAccessLayer
{
public class GiftDAL : SqlDataAccessLayer
{
    public bool UpdateGift(Gift GifttoUpdate)
    {
        string UpdateString = "";
        UpdateString += "UPDATE Gifts SET";
        UpdateString += "GiftName = @GiftName";
        UpdateString += ",Description = @Description ";
        UpdateString += ",Price = @Price ";
        UpdateString += " WHERE GiftID = @GiftID";

        int RowsAffected = 0;

        try
        {
            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(UpdateString, con))
                {
                    cmd.Parameters.AddWithValue("@GiftName", GifttoUpdate.GiftName);
                    cmd.Parameters.AddWithValue("@Description", GifttoUpdate.Description);
                    cmd.Parameters.AddWithValue("@Price ", GifttoUpdate.Price);
                    cmd.Parameters.AddWithValue("@GiftID", GifttoUpdate.GiftID);
                    con.Open();
                    RowsAffected = cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            Utils.LogError(ex.Message, ex.InnerException == null ? "N/A" : ex.InnerException.Message, ex.StackTrace);
        }

        return (RowsAffected == 1);

    }

    public void DeleteGift(Gift GifttoDelete)
    {
        string DeleteString = "";
        DeleteString += "DELETE FROM GIFTS WHERE GIFTID = @GiftID";

        try
        {
            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(DeleteString, con))
                {
                    cmd.Parameters.AddWithValue("@GiftID", GifttoDelete.GiftID);
                    con.Open();
                    cmd.ExecuteNonQuery();

                }
            }
        }
        catch (Exception ex)
        {
            Utils.LogError(ex.Message, ex.InnerException == null ? "N/A" : ex.InnerException.Message, ex.StackTrace);
        }
    }


}
}

So looking at that, how would you recommend I improve the code (if I continue to use ADO.NET) and what would my next step be to learn EF - or is there a better alternative?

Cheers, Robbie

One thing that's always important (to me) is how testable a class is. I see a lot of explicit object construction in your code. Your Gift BL class explicitly depends on GiftDAL, which makes it very difficult to test the Gift class. Try to reduce the coupling between classes by making an abstraction of GiftDAL (e.g. an interface) and provide that to Gift from the outside (Dependency Injection).

A great book about good software design principle is Clean Code by Robert C. Martin. He establishes the SOLID principles. Check it out!

Also, be aware that you are now including persistence within your business logic class (or domain model as it is also called). This can be done (Active Record), but often people choose for a different approach nowadays where they separate their domain model from any infrastructure. The broad idea is: the fact that the objects need somehow be stored is important, but not important for the business logic itself, so those to concerns should be separated where possible. Often an Object Relational Mapper, for .NET NHibernate or Entity Framework are two examples for OR mappers.

Let's say I want to define some methods and helpers that will be available across all my ActiveRecord models.

A bit of research tells me there are two general options

Module

Define a module

module MyModule
  def foo
    # ...
  end
end

Include it in the model when you need it

class User < ActiveRecord::Base
  include MyModule

  before_save :foo
end

Inheritance

Define a base class

class BaseModel < ActiveRecord::Base
  # Define as abstract so AR doesn't assume there's a table named `base_models`
  self.abstract_class = true

  def foo
    # ...
  end
end

Make all models inherit from it

class User < BaseModel
  include MyModule

  before_save :foo
end

What are the pros/cons to each - is there any particular advantage in doing it one way? Is there one that's more considered the "Rails way" ?

Thanks!

It is always better to use relationship between classes/modules that is called has instead off is.

Or in other words it is better to use Module instead off the inheritance. This is because of latter possible changes, what if you later on the road get requirement to have 2 types of classes, you would have to create 2 BaseClasses, and let some classes inherit from one, and other from another.

When you are using modules, you just include the module, and thus you define the behaviour of the class that includes it, the so called has behaviour.

To get a good grasp of what is good in code, and what is not, learn Patterns, and read Clean Code

My search method is smelly and bloated, and I need some help refactoring it. I'm new to Ruby, and I haven't figured out how to leverage it effectively, which leads to bloated methods like this:

  # discussion.rb
  def self.search(params)
    # If there is a search query, use Tire gem for fulltext search
    if params[:query].present?
      tire.search(load: true) do
        query { string params[:query] }
      end

    # Otherwise grab all discussions based on category and/or filter
    else

      # Grab all discussions and include the author
      discussions = self.includes(:author)

      # Filter by category if there is one specified
      discussions = discussions.where(category: params[:category]) if params[:category]

      # If params[:filter] is provided, user it
      if params[:filter]
        case params[:filter]
        when 'hot'
          discussions = discussions.open.order_by_hot
        when 'new'
          discussions = discussions.open.order_by_new
        when 'top'
          discussions = discussions.open.order_by_top
        else
          # If params[:filter] does not match the above three states, it's probably a status
          discussions = discussions.order_by_new.where(status: params[:filter])
        end
      else

        # If no filter is passed, just grab discussions by hot
        discussions = discussions.open.order_by_hot
      end
    end
  end

  STATUSES   = {
    question:   %w[answered],
    suggestion: %w[started completed declined],
    problem:    %w[solved]
  }

  scope :order_by_hot,  order('...') DESC, created_at DESC")
  scope :order_by_new,  order('created_at DESC')
  scope :order_by_top,  order('votes_count DESC, created_at DESC')

This is a Discussion model that can be filtered (or not) by a category: question, problem, suggestion.

All discussions or a single category can be filtered further by hot, new, votes, or status. Status is a hash in the model and it has several values depending on the category (status filter only appears if params[:category] is present).

Complicating matters is a fulltext search feature using Tire

But my controller looks nice and tidy:

  def index
    @discussions = Discussion.search(params)
  end

Can I dry this up/refactor it a little, maybe using meta programming or blocks? I managed to extract this out of the controller, but then ran out of ideas. I don't know Ruby well enough to take this further.

For starters, "Grab all discussions based on category and/or filter" can be a separate method.

params[:filter] is repeated many times, so take that out at the top:

filter = params[:filter]

You can use

if [:hot, :new, :top].incude? filter
  discussions = discussions.open.send "order_by_#{filter}"
...

Also, factor out if then else if case else statements. I prefer break into separate methods and return early:

def do_something
  return 'foo' if ...
  return 'bar' if ...
  'baz'
end

discussions = discussions... appears many times, but looks weird. Can you use return discussions... instead?

Why does the constant STATUSES appear at the end? Usually constants appear at the top of the model.

Be sure to write all your tests before refactoring.

To respond to the comment about return 'foo' if ...:

Consider:

def evaluate_something
  if a==1
    return 'foo'
  elsif b==2
    return 'bar'
  else
    return 'baz'
  end
end

I suggest refactoring this to:

def evaluate_something
  return 'foo' if a==1
  return 'bar' if b==2
  'baz'
end

Perhaps you can refactor some of your if..then..else..if statements.

Recommended book: Clean Code

Please allow my intro to properly define the scope of my question:

I'm still very new to the programming world. This all started for me when I had an idea for a software program, but no programming experience. I ended up going the outsourcing route to get the program, and after almost a year, we do have it live and functioning.

This specific program is written with php and is 100% web-based. We're using lots of ajax, jQuery, etc.

Now a year into it, I have been learning and learning wherever I can (lots of learning here!!!) I'm mainly focusing on Java now to build up to Objective-C and the iPhone fun (probably like 99% of all other newbie programmers out there).

I'm really learning so much, and one of the biggest things I'm learning about is proper commenting and scalability.

I'm seeing now that this job we just finished is very sorely lacking in both those areas. I am wanting to add and build upon this program, and not only do I not have much experience, but I'm seeing that it's really hard for me to even get an idea about the functions without these comments...

So my question is-what is the best course of action to begin to pick up the pieces on this program? A full re-write is out of the question, and I don't think is needed.

I'm sure this is not the first time some newbie programmer, software developer has been down this path...what do others do here?

Is it common for a programmer to come into a project very far along and then "clean up" the mess in order to make things move forward productively?

If this is the wrong place for this question (and I understand it may well be) can someone point me to where this would be more appropriate?

Thanks! Joel

I'm really learning so much, and one of the biggest things I'm learning about is proper commenting and scalability.

First, I'm curious what you've learned about "proper commenting" as this varies drastically. For some, it's documenting every class and function. For others, it may be documenting every line of code or no code at all.

After having gone through some of the different phases above, I'm with Uncle Bob Martin who, in Clean Code, says that you document decisions, not what the code does. The code itself should be readable and not need documentation. By adding comments describing behavior, you've created duplication that will eventually become out of sync. Rather, the code should document itself. Using well-named functions and variables help describe exactly what the other intended. I'd highly recommend Clean Code for a full discussion of these concepts.

As for scalability, it's usually something that you want to build in. Scalability might be a function of good design, or a proper design for the requirements, but poor design will make scalability a nightmare.

I'm seeing now that this job we just finished is very sorely lacking in both those areas. I am wanting to add and build upon this program, and not only do I not have much experience, but I'm seeing that it's really hard for me to even get an idea about the functions without these comments...

I see this as an indicator of one of two things:

  1. That the code isn't well written. Yeah, that's highly subjective. -OR-
  2. That you don't yet fully understand everything you need to. -OR-
  3. A little bit of both.

Writing good, intention-revealing code is hard and takes years of practice.

So my question is-what is the best course of action to begin to pick up the pieces on this program? A full re-write is out of the question, and I don't think is needed.

As other posters have mentioned, Refactoring. Refactoring is the process of changing code to improve readability and usability without changing functionality. Get a good book on refactoring, or start reading everything you can online. It's now a critical skill.

Is it common for a programmer to come into a project very far along and then "clean up" the mess in order to make things move forward productively?

Unfortunately it is. It takes a lot of diligence to avoid falling into this trap. Try to make your code a little bit better every day.

Recently I read a book(CleanCode)

in this book,

FUNCTION SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.

and function should be small.

But I think the function in javascript.

If I split big function to small things, the code is getting longer and It takes more time to render.

Is it better to make function small even in javascript?

What is your opinion

Micro-optimizations are not worthwhile. Maintainability is far more important. For actually serving the code to the browser, you can use a JavaScript minifier.

So, I'm developing some software, and trying to keep myself using TDD and other best practices.

I'm trying to write tests to define the classes and repository.

Let's say I have the classes, Customer, Order, OrderLine.

Now, do I create the Order class as something like

abstract class Entity {
    int ID { get; set; }
}

class Order : Entity {
    Customer Customer { get; set; }
    List<OrderLine> OrderLines { get; set; }
}

Which will serialize nice, but, if I don't care about the OrderLines, or Customer details is not as lightweight as one would like. Or do I just store IDs to items and add a function for getting them?

class Order : Entity {
    int CustomerID { get; set; }
    List<OrderLine> GetOrderLines() {};
}

class OrderLine : Entity {
    int OrderID { get; set; }
}

And how would you structure the repository for something like this?

Do I use an abstract CRUD repository with methods GetByID(int), Save(entity), Delete(entity) that each items repository inherits from, and adds it's own specific methods too, something like this?

public abstract class RepositoryBase<T, TID> : IRepository<T, TID> where T : AEntity<TID>
{
    private static List<T> Entities { get; set; }

    public RepositoryBase()
    {
        Entities = new List<T>();
    }

    public T GetByID(TID id)
    {
        return Entities.Where(x => x.Id.Equals(id)).SingleOrDefault();
    }

    public T Save(T entity)
    {
        Entities.RemoveAll(x => x.Id.Equals(entity.Id));
        Entities.Add(entity);
        return entity;
    }

    public T Delete(T entity)
    {
        Entities.RemoveAll(x => x.Id.Equals(entity.Id));
        return entity;
    }
}

What's the 'best practice' here?

Why not create separate Order classes? It sounds to me like you're describing a base Order object, which would contain the basic order and customer information (or maybe not even the customer information), and a separate Order object that has line items in it.

In the past, I've done as Niels suggested, and either used boolean flags or enums to describe optionally loading child objects, lists, etc. In Clean Code, Uncle Bob says that these variables and function parameters are excuses that programmers use to not refactor a class or function into smaller, easier to digest pieces.

As for your class design, I'd say that it depends. I assume that an Order could exist without any OrderLines, but could not exist without a Customer (or at least a way to reference the customer, like Niels suggested). If this is the case, why not create a base Order class and a second FullOrder class. Only FullOrder would contain the list of OrderLines. Following that thought, I'd create separate repositories to handle CRUD operations for Order and FullOrder.

What is the best way to define a method signature when you have to pass many values to a function and some of these may be optional. And in future, May be I have to pass more variables or subtract some passed values given to function.

For example: (phone and address are optional)

function addInfo( $name, $dob, $phone='', $address='' ) {
       // Store data
}

addInfo( 'username', '01-01-2000', '1111111' ); // address is not given

OR

function addInfo( $info ) {
    // Store data
}

$info = array( 'name'=>'username', 
               'dob'=>'01-01-2000', 
               'phone'=>'1111111', 
               'address'=>'' );
addInfo( $info );

Martin suggests in "Clean Code", that you should limit the number of parameters atmost to 2-3 to keep the code easily understandable. So it would be better to wrap them into an object and pass the object as parameter. It's definitely preferable.

After finishing a big project I am trying to make the code proper. I've took a look at Clean Code and i'am now doing my best to apply conscientiously the rules. I'am done with naming, commenting, testing etc.

I'am now trying to refactor the code. I have multiple sheets, with multiple zone containing thousands of cells. I am doing similar things on each zone so I tried to use general function instead of some lines of codes adapted to each zone. I've encoutered 2 problems depending on how I work.

Here is a simple exemple:

Before witing things in cells I want to clear them.

First option:

I loop trough zone and clear them.
      for each Zone in Zones
            zone.clearcontents
            [work on zone]
            for each cell in cells
                [work on cells]
            next
       next

This used to work, but after a second launch I got the error "too many different cells formats", I didn't know how to handle that so I've tried to go that way:

for each Zone in Zones
        [work on zone]
        for each cell in cells
        cell.clearcontents
            [work on cells]
        next
next

But now I've an error with merged cells, "cannot change parts of merged cells".

I don't know how to optimize the code, keep it simple and handle those errors. How would you manage to solve this problem ?

Currently I am working on a bit of code which (I believe) requires quite a few embedded if statements. Is there some standard to how many if statements to embed? Most of my googling has turned up things dealing with excel..don't know why.

If there is a standard, why? Is it for readability or is it to keep code running more smoothly? In my mind, it makes sense that it would be mainly for readability.

An example of my if-structure:

if (!all_fields_are_empty):
    if (id_search() && validId()):
        // do stuff
    else if (name_search):
        if (name_exists):
            if (match < 1):
                // do stuff
        else:
            // do stuff
    else if (name_search_type_2):
        if (exists):
            if (match < 1):
                // do stuff
        else:
            // do stuff
else:
    // you're stupid

I have heard that there's a limit to 2-3 nested for/while loops, but is there some standard for if-statements?

I don't think there is a limit but i wouldn't recommend embeddeding more the two - it's too hard to read, difficult to debug and hard to unit test. Consider taking a look at a couple great books like Refactoring, Design Patterns, and maybe Clean Code

DDD Newbie question:

I read in a blog somewhere that in a scenario where objects are closely associated with each other in a domain driven design, and where one object based on some complicated business rule is responsible for the creation of a dependent object, in such a design the usefulness of dependency injection is very limited.

Would you agree?

No, I wouldn't agree.

The whole purpose of DDD is to arrive at an expressive model that facilitates change. It is accepted as a given that business logic often changes, so the model must be flexible enough to enable a quick change of direction in the face of changing requirements or new insight.

As Uncle Bob writes in Clean Code, the only way to enable a flexible and expressive API that can quickly address unprecedented change is to use loose coupling. Loose coupling is achieved through the Dependency Inversion Principle; from there, the connection to DI follows naturally.

As I read Domain-Driven Design, this was always the underlying motivation behind all the talk about Factories, but I personally find the book a little vague there.

I am using Junit for the first time in a project and I'm fascinated by the way it is forcing me to restructure my code. One thing I've noticed is that the number of objects I've created in order to be able to test chunks of code is significantly increasing. Is this typical?

Thanks,

Elliott

Yes, this is normal.

In general the smaller/more focused your classes and methods are, the easier to understand and test them. This might produce more files and actual lines of code, but it is because you are adding more abstractions that makes your code have a better/cleaner design.

You may want to read about the Single Responsibility Principle. Uncle Bob also has some re-factoring examples in his book called Clean Code where he touches on exactly these points.

One more thing when you are unit testing. Dependency Injection is one of the single most important thing that will save you a lot of headaches when it comes to structuring your code. (And just for clarification, DI will not necessary cause you to have more classes, but it will help decouple your classes more from each other.)

I developed a medium sized MS Access application back in 2004. Over the years it has grown old and my small bugfixes and improvements don't cut it anymore.

I always hear people yammering about how bad Access is and how it is not modern yadda,yadda. I'm quite happy with it and it does what it is supposed to do (Provide a stable frontend for a simple database).

My application uses lots of custom forms with subforms and lots of VBA code to do this and that. The most important part of the application is actually to provide the data for Word Mail Merges and to print badges and other material for a conference (via Access reports). And exactly this printing integration is why I can't think of any alternatives.
Any web based solution will be a hassle to create nice looking reports (or at least not with the easy of Access) - create pixel perfect layouts and mold them into PDFs, direct printing FTW. Any Windows Forms application will take long to develop and ultimately I would just be recreating functionality of MS Access (e.g. together with SSRS).

Can you think of any alternatives I have missed? I am basically just looking for ideas.

Well, if you use built in functionality in Access the best path might be to not abandon Access but rather to rebuild the application as a new Access pplication.

Start by breaking out parts of the applicatin to classes to get all related code together and clean up that code.

This way you could still use the parts of access you realy have use for but the code will be better.

Also take a look on a book I like, Clean Code

Here is some other talk about this book.

Refactoring code like this is also a good way to get to know all the intricate parts of it ;)

And you will not risk loosing any functionality.

If you later get to build it on another platform, most of the refactoring would probably be reusable.

If I have a method that operates exclusively on a reference type variable (e.g. a datatable) and modifies it, is there any need to return that variable from the method??

For example, the following method goes through a datatable and trims all the values within it and then returns the datatable to the caller:

        private DataTable TrimAllDataInDataTable(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    row[dc] = row[dc].ToString().Trim();
                }
            }

            return dt;
        }

Would it be better if this method returns void? Seems pretty pointless to return it (?), but do you think that it reads better if it returns the object after operating on it (like it does at the moment)??

Arguments as outputs could be considered confusing as more often that not in OO programming we'd expect arguments to be used as inputs not outputs. Another approach suggested by Clean Code would be to make the variable being modified a member of a class:

class DataTableTrimmer {

    private DataTable dt;

    public DataTableTrimmer(DataTable pDt) {
        dt = pDt;
    }

    public void TrimAllDataInDataTable()
    {
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn dc in dt.Columns)
            {
                row[dc] = row[dc].ToString().Trim();
            }
        }
    }

    ...
}

I guess in almost every programm sometimes methods don't need to be called all the time but under specific conditions only. It it very easy to check if a method must be called. A simple if-statment can do the trick.

if (value == true)
{
    DoSomething();
}

But if you have many conditions the validation can get complicated and the code gets longer and longer. So I wrote code with the method called every time and the method itself will check and validate if her code needs to be executed.

DoSomething(value);

... then ...

public void DoSomething(bool value)
{
    if (value == true)
    {
    // Do Something here ...
    }
}

Now I have two ways of doing things. I am not exactly sure which way is the right way. Or maybe there is even another option?

Clean Code — A Handbook of Agile Software Craftsmanship promotes not to write methods accepting a single boolean parameter because each method should do one thing and one thing only. If a method takes a boolean parameter to decide what to do, it automatically does two things: deciding what to do and actually doing something. The method should be refactored into two separate methods doing something and a single method deciding which of the two methods to call.

Furthermore, evaluating a boolean value using value == true is redundant and unnecessary. The value itself represents a boolean state (true / false) and does not need to be compared to true again. That said, the best practice is using if (value) instead of if (value == true) (or if ((value == true) == true; this seems idiotic but does not differ much from the approach of if (value == true)).

I have checked many books but couldn't find any good book. I am interested in book from where I can learn OOP concepts with examples in an easy way. Book like Java Black book

I can recommend Pro C# 2010 and the .NET 4 Platform for learning OOP with C# - I have the 2008 version of that book and it covers all the fundamentals - and once you got those down, the book offers much more as well.

Two excellent books that I would recommend are:

CLR via C# by Jeffrey Richter

and

Clean Code by "Uncle" Bob Martin

Richter's book will give you all of the details about the aspects (programming and OOP capabilities) of C#, and Martin's book will give you guidelines on writing proper code in an OO environment. Martin's book is geared towards Java, but the concepts apply equally to C# (IMHO).

The Head First OOA&D book that Mitch mentions in comments is also excellent. Probably the combination of all three will make you unstoppable. :)

Hope this helps!

I have entities that are very dumb and only holds the data. I used to put some business logic inside the entities or presenter, i.e.

  • Movie.findMostWatchedTopTenMovies
  • Movie.hasWatchedThisMovie
  • TheatrePresenter.canScreenMoreMovies

(assume that these method contains some complex logic and it's not just getter)

but this seems against the SOLID principle and it's not test friendly code. So where is the most appropriate place to put this logic? And what should the class name be?

You are correct, It is against SOLID principle and your Models must be atomic, which means they only hold values and do not do any changes by themselves.

By referencing to Clean Code book, You must declare some classes that do the changes you want with relevant names, for instance:

class MovieFinder{
    public static List<Movie> findMostWatchedTopTenMovies(List<Movie> moviesList){

    // do the fining stuff

    return mostWatchedTopTenMoviesList;
    }
}

and even the best thing to do is to crate a new list of items and return it as a result.

Also, for having a pure atomic model you can use google AutoValue library which stops you from doing unusual things with models. ;)

I'm a mostly self taught programmer and one aspect I've never really understood is how to return data (term used loosely) and a status message from a method.

For example, say I have a method that takes a search term and returns the result of a query. If the caller gets an empty dataset back, how would it know if it's empty because there are no matches or empty because there was an error in the connection to the database.

I've used APIs where an out or ref parameter was used, but it seems less than ideal. Perhaps this is the whole point of exceptions. The method would throw an exception if it can't connect to the db, so the caller would know if it received no results and no exceptions then there were simply no results. Would I create my own object that contained both the data an a status message?

Maybe I'm overthinking this or am missing some fundamental point of OOP.

I'm looking to understand what the best way of returning status or error messages AND data from a method.

I wasn't sure if this belonged on Programmers or StackOverflow since it could be considered subjective, sorry if Stack is the wrong place for it.

That is part of the point of exceptions.

In his book Clean Code the author talks about how it can cause confusion to start having out parms, or return values on what would otherwise be void methods.

It makes it harder to understand code just by reading it.

For example people.Find("John") should return a list of Johns, or a single John or throw an exception.

The caveat here is that exceptions can be expensive and so you don't want to use them for control flow.

So for searching, if it doesn't matter WHY there are no results, then just return null (or an empty list.)

I'm new to asp.net MVC and EF, so excuse me if my question is not clear or easy.

I have read some tutorials about EF Code-First approach and now I'm trying this tutorial Getting Started with EF using MVC.

Using Code-First approach I'm using the POCO classes to define my DB model, DB logic, DB validation, UI validation and some UI logic. So I can use these classes(or objects) in my presentation layer or use them as JSON objects when dealing with Web-Services(or in JavaScript code).

My question: Isn't that mixing some logic together? I mean shouldn't I use like special view-model classes for presentation and these classes should have the UI logic and validation ?!

Is it good practice to send the POCO object to the view(or to the client in general) ?

Finally i need some guidance on how to organize my project layers or folders? I see many ways and I'm confused about what to choose or what format I should base my own on?!!

You should not use your data entities in higher layers of your application. Transform/compose/copy data from DAL into view model or business classes using a library like Automapper. This keeps the layers of your application independent and hides your database schema from end users.

Keep in mind that MVC is only concerned with presentation, all real work should happen in other layers of your app. I try to keep layers independent and use a little bit of glue code to bundle them into an app. I may write data access and business logic layers when working on MVC project, but then re-use in a command line utility. There are a lot of books that talk about writing quality code. I personally found Clean Code, Code Complete 2, and Design Patterns extremely helpful.

In the book Clean Code the author recommends breaking large methods into small functions that do one specific thing. In languages like Java this translates to pretty, readable code.

public static String renderPage(PageData pageData)
{
    includeHeader(pageData);
    includeContent(pageData);
    includeFooter(pageData);
    return pageData.getHtml();
}

However in Objective-C as far as I know the only way to implement functions like this are to create private methods and call them by messaging self

- (NSString *)renderPageWithData:(PageData *)pageData {
    [self includeHeader:pageData];
    [self includeContent:pageData];
    [self includeFooter:pageData];
    return [pageData HTML];
}

I feel like messaging self implies some sort of operation that the object is doing to itself. C functions aren't really an option because the don't fall under the scope of the class. Meaning I can't access any of the instance variables or the class object with out doing extra legwork, and adding complexity.

I'm looking for a good way to create clean code with regard to functions or methods in Objective-C

I see your point about the function calls: self and include in the same "sentence" make it look as though things are being included in the class itself. I would solve that with more explicit method names:

- (NSString *)renderPageWithData:(PageData *)pageData {
    [self renderHeaderWithData:pageData];
    [self renderContentWithData:pageData];
    [self renderFooterWithData:pageData];
    return [pageData HTML];
}

I use a string type for my Id attribute on all my domain abjects. E.g.:

public class Person {
    property string Id { get; set; }
    // ... more properties
}

no tricks here. null represents a "no-value" value, when a new Person is created and before it is persisted, Id will remain null.

Now there is a discussion to enhance "no-value" space and say that null, empty string and white-space strings are all "no-value" values.

I.e. to check if entity is new instead of doing: if (person.Id == null) it will become if (string.IsNullOrWhiteSpace(person.Id))

In my humble opinion this is a smell or a design principle violation, but I can't figure out which one.

Question: which (if any) design principle does this decision violate (the decision to allow for more than just null to represent no-value value)?

(I think it should be something similar to Occam's razor principle or entropy or KISS, I just not sure)

It does violate the KISS principle. If there is no special need for handling empty strings beside nulls, then why do it? All operations must now check for two values, instead of one. When exploring the DB, a simple SELECT to find "NULL" records, becomes slightly less trivial for no good reason.

Another violated principle is the principle of least surprise - usually people expect only NULL values to represent NULL objects. The design with two special values is less obvious, and less "readable".

If something more should be hidden behind these "second-category-special-objects", then it should be made explicit. Otherwise, it should be trivial to handle empty string input, and store it as NULL to be coherent with the rest of the system.

EDIT:

I've also found another "principle" in Bob Martin's book Clean code - "one word per concept" which is somehow related to this case. Empty string and a NULL are two "words" used for one concept so they clearly violate this guideline.

I've just finished Clean Code and one of the precepts is to avoid passing boolean arguments as functional selectors, e.g.,

Instead of this:

public double calculateWeeklyPay(boolean overtime) {
    double pay = calculatePay();
    if (overtime) {
         return pay *= 1.5;
    }
    return pay;
}

We should do this, and let the consumer call the appropriate method:

public double calculateWeeklyPay() {
    return calculatePay();
}

public double calculateWeeklyPayWithOvertime() {
    double pay = calculateWeeklyPay();
    return pay *= 1.5;
}

But what should I do in more complicated methods where splitting up the method will mean lots of duplicate code?

What should be done here:

public double calculateWeeklyPay(boolean overtime) {

    double pay = calculatePay();
    pay = modifyPay1(pay);
    pay = modifyPay2(pay)
    pay = modifyPay3(pay)
    if (overtime) {
        pay = pay *= 1.5;
    }
    pay = modifyPay4(pay);
    pay = modifyPay5(pay);
    pay = modifyPay6(pay);

}

You have to distinguish between the public API and the internal API.

For the public API you really should avoid such selector arguments. But for an internal API (the private methods) it is an appropriate mechanism for implementation. So make it like this:

public double calculateWeeklyPayWithOvertime() {
    return calculateWeeklyPay(true);
}

public double calculateWeeklyPayWithoutOvertime() {
    return calculateWeeklyPay(false);
}

private double calculateWeeklyPay(boolean overtime) {
    double pay = calculatePay();
    if (overtime) {
         pay *= 1.5;
    }
    return pay;
}

I've read a lot of Refactoring literature as of late and a common theme I see in examples is the reduction of lots of IF statements. The below is a very simple code block that first checks to see if an email address is supplied and if so, then proceeds to validate the email address. I typically see a lot of this type of code which always looks a bit messy, especially if there are multiple variables.

if (string.IsNullOrEmpty(email)) {

    throw new ApplicationException("Email Address Required");
}

else {

    if (!ValidationService.EmailAddressIsValid(email)) {
        throw new ApplicationException("Invalid Email Address");
    }

}

My question is, is this example perfectly acceptable? Does it smell? How might one refactor this snippet?

If you would really like to make your code readable, you could even do something like this:

throwExceptionIfEmailIsEmpty(email);
throwExceptionIfEmailIsInvalid(email);
// continue to process the e-mail here...

With this code extracted into separate functions:

private void throwExceptionIfEmailIsEmpty(String email)
{
    if (string.IsNullOrEmpty(email))
        throw new ApplicationException("Email Address Required");
}

private void throwExceptionIfEmailIsInvalid(String email)
{
    if (ValidationService.EmailAddressIsValid(email))
        throw new ApplicationException("Invalid Email Address");
}

It might seem a bit excessive, but it makes it much easier to see what's really going on!
(Inspired by Uncle Bob's Clean Code - Functions should do one thing. They should do it well. They should do it only. (or something like that) - if anyone wondered ;))

I was looking at a javascript library and noticed that you can access arguments passed to a function using an arguments array like so...

function foo() {
    var firstArg = arguments[0];
    var secondArg = arguments[1];
    //code
}

I had always done this by specifying parameters right in the function definition

function foo(firstArg, secondArg) {
    //code
}

What are the advantages/disadvantages of these two strategies for reading function arguments?

I always like to specify the parameters to my functions because it is more readable and clear. Particularly i don't like to use arguments[] because I don't know who is arguments or arguments[0].

But if i need to pass a lot of parameters to a function?

In this case a recommend, think about your function, it is probably breaking the concept of Single Responsibility Principle. And Read Clean Code book will help.

This is my opinion.

this is a general question regarding method block structures. Does anyone have an opinion on what is a better way to design methods given the 2 alternatives below?

private void Method1()
{
    if (!A)
    {
        return;
    }

    if (!B)
    {
        return;
    }

    if (!C)
    {
        return;
    }

    // DO WORK.......

    return;
}

private void Method2()
{
    if (A)
    {
        if (B)
        {
            if (C)
            {
                // DO WORK.......

                return;
            }
        }
    }

    return;
}

The first method is debatable - personal preference to have multiple conditions or a single OR.

However the second method is bad, bad, bad. Multiple levels of indentation in a single method is just asking for bugs - maintainability and readability go way down. This is well-known, widely written about and documented.

This is a simple style question. What is the preferred means for declaring access controls in Ruby code?

Example A:


#!/usr/bin/env ruby

class MyClass
    def method1    # this is public by default
        #...
    end
    protected      # subsequent methods will be protected
        def method2
            #...
        end
    private        # subsequent methods will be private
        def method3
            #...
        end
    public         # subsequent methods will be public
        def method4
            #...
        end
end

or Example B:


#!/usr/bin/env ruby

class MyClass
    def method1
        #...
    end
    def method2
        #...
    end
    def method3
        #...
    end
    def method4
        #...
    end
    public :method1, :method4
    protected :method2
    private :method3
end

Syntactically, I like Example B. A introduces ambiguity between public methods declared after protected/private methods, although I see no reason why you shouldn't just call method1 after specifying it as being public.

This isn't however about what I like. What is the industry defined norm for this?

I think it really depends on your coding style. If you read "Clean Code" by Uncle Bob, you (which I personally loved), you're encouraged to write methods or functions that are called by each other closely together. In this case, using the visibility of a method as in example B would make sense:

class Foo
  def method1
    method2
  end

  def method2
    ..
  end
  private :method2
end

Uncle Bob actually makes a good case for having methods close together, since this prevents scrolling in your code.

This program that checks if there is any repeated username present in the database. The problem is it repeats the insert n times, depending on the number of current usernames in the database.

Here is the code:

ResultSet rs = SQLOperations.getAllUser(connection);            
while (rs.next()) {
  String user=rs.getString("username");
  if (username.equalsIgnoreCase(user)) {
    System.out.println("same username"); 
  } else {
    if(!password.equals(cpassword)) {
      System.out.println("not the same pass and cpass");
    } else {
      if (connection != null) {
        if (SQLOperations.addAccount(account, connection)) {
          System.out.println("successful insert");
        } else {
          System.out.println("failed insert");
        }
      } else {
        System.out.println("invalid connection");
      }

Your actual problem is a design problem. Your methods should do exactly one thing and one thing only. In this program, there are three things being done: checking the database for other accounts and inserting an account, while the third thing is checking for connections. Instead:

//This function checks to see if a user exists
public boolean userExists(Connection conn, String username) {
  ResultSet rs = SQLOperations.getAllUser(connection);            
  while (rs.next()) {
    String user=rs.getString("username");
    if (username.equalsIgnoreCase(user)) {
      return true;//This is the only thing we care about
    }
  }
  return false;//We didn't find a duplicate username.
}

//This is our gateway function, but it actually is doing validation
public void insertNewUser(Connection conn, String username, String password, String confirmpassword) {
  if (userExists(conn, username) { //Note this is our validation logic
    System.out.println("Same username! Cannot add this account.");//probably should be an exception or return value, not println
  } else { //we have validated the user, now validate password
    if(!password.equals(cpassword)) {
      System.out.println("not the same pass and cpass");
    } else {
      if (addUser(Connection conn, String username, String password)) {
        System.out.println("Successfully added.");
      } else {
        System.out.println("Attempt to add user to db failed.");
      }
    }
  }
} //note that we do nothing else in this function!

//Note this function assumes you've already run a validation check
private boolean addUser(Connection conn, String username, String password) {
  if (connection != null) {//I think this is probably not the right place for this, but sure.
    if (SQLOperations.addAccount(account, connection)) {
      return true;
    } else {
      return true;
    }
  } else {
    return false;
  }
}

Note each function does exactly one thing (except for the last function, which should really be two functions or have intelligent exceptions to handle the dead connection case). By doing this you keep your code much cleaner. In fact, this code becomes even cleaner if you do use exceptions, and an exception-handling function. I highly recommend Clean Code as a book that will help you think more critically about this stuff.

Where to read up on (the best-practice in) source code formatting, for individual languages i.e. what are the conventions for naming variables etc., for indentation and where to place braces, how and where to include comments, etc.

For example for C Kernighan and Ritchie's book The C Programming Language and Linus Torvalds' Linux kernel coding style guide or Google's C++ Style Guide and for Perl at least perlstyle - Perl style guide.

Edit: Perhaps I should have asked "How to get a good start with coding styles".

I wouldn't give too much on such style-guides. They are a good start, but in the end you or your team will develop own coding-styles.

EDIT: Rob Kam made a comment, that he want to find out more about these 'starting-conventions'.

That's a good point. But mostly you will join existing projects, open-source-projects or commercial, and the people working on it already have a code-convention. In a company probably exists already a code convention. If you start a new project, start with the conventions of another project you did before.

If you really start a new project with a new language you didn't used before ... then you might start with conventions of another language that is somehow similar (i.e. for a new oo-language you can use conventions from Java or Smalltalk) and adjust your conventions as you gain experience for the new language. As I started programming in Java I used my Pascal-coding-conventions. Some of the pascal-conventions didn't work very good for Java, but with the time I dropped some old conventions and developed new.

S.Lott had the idea to look into an open-source-project written in the language of your choice. That's a good idea to get some suggestions about good conventions. Srikanth had the good idea to ask for good conventions here at Stackoverflow. A very good idea, because with the time Stackoverflow will become a good reference for coding-conventions this way.

I would really recommend to read uncle bob's Clean Code if you are concerned about code style issues.

C# code can be separated into regions by using the #region and #endregion tags.

Can the same be done for JavaScript code ? I have a file with some 1100 lines and it's getting hard to manage it.

Even if you would have #region and #endregion for Javascript this would not solve your problem. You should focus on separating the whole logic into separate files and make that each JS file is responsible for a certain piece of work. Believe me - this will considerably improve the readability of your code and make it much more maintainable. I recommend to read this book (although it is not stricly about JS, but about writing in general): http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Do you think it's a good practice to differentiate abstract from non-abstract classes by giving their name a prefix or a suffix? What are the most common practices when it comes to that?

Here are a few "formats" I've been thinking about:

  • Foo_Base
  • Foo_Abstract
  • Abstract_Foo
  • Base_Foo

The use of underscores and letter case is irrelevant.

Edit: It seems like the Zend Framework uses a "Abstract" suffix (source).

I think it is bad practice to name variables/functions/classes based on the type that it represents. int myInt is good for coding a quick example (perhaps in a classroom setting) but thats about it.

abstract class AbstractClass is too redundant and annoying to read. Let your programs/code say a lot in a concise way, and speak for themselves. From reading the definition I know its an abstract class I shouldn't need to be reminded in the name of the class. Focus on what purpose the class has in reference to the problem instead of what type of class it is.

This is the gist of things I got from Clean Code

If you describe the project I can suggest good names that aren't redundant.

(EDIT** I was able to get the code to compile and execute a unit test that passed. In addition to the code fixes, there was a problem with VS2010 running the unit test indefinitely. I had to replace a dll file that was changed during an aborted install of vs 2012. I posted the changes to the controller and unit test at the bottom of the page. Thanks to all who posted answers.)

This is the first question I've ever asked online about coding. I've been learning C# .NET and other associated stuff using free tutorials for about a year now. So far I've been able to research and troubleshoot everything on my own. I'm starting to venture into uncharted territory now and I can't seem to find an answer.

I have been working on a tutorial called "Learn MVC Model View Controller Step by Step in 7 days". Here is the link: http://www.codeproject.com/Articles/259560/Learn-MVC-Model-view-controller-Step-by-Step-in-7

I have researched the suggested links for the error:

Error 'Mvccustomer.Models.Customer' does not contain a definition for 'DisplayCustomer'        and no extension method 'DisplayCustomer' accepting a first argument of type     'Mvccustomer.Models.Customer' could be found (are you missing a using directive or an     assembly reference?)

The problem I'm running into is that I can't seem to find a similar situation where someone is creating a unit test with a similar file reference. Mind you, I'm totally new to MVC and unit testing.

One problem with the tutorial is that that in the videos the author uses one set of namespaces/file names and another in the written tutorial. I was able to troubleshoot that problem on my own. For instance, in the beginning, he uses 'Mvccustomer' as a project name but by the 4th or 5th lab on the first day he's calling it 'Mvcinputscreen'. I susspect that the trouble lies in how the customer class is referenced in the project but I can't figure it out so far.

Here is the unit test that gives me an error:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mvccustomer.Models;

namespace MvcUnitTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void DisplayCustomer()
        {
            Customer obj = new Customer();
            var varresult = obj.DisplayCustomer();
            Assert.AreEqual("DisplayCustomer", varresult.ViewName);
        }
    }
}

Here is the customer class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvccustomer.Models;

namespace Mvccustomer.Models
{
    public class Customer
    {
        public int Id { set; get; }
        public string CustomerCode { set; get; }
        public double Amount { set; get; }
    }
}

This is the Display Customer View:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Mvccustomer.Models.Customer>"     %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>DisplayCustomer</title>
</head>
<body>
    <div>
    The customer id is <%= Model.Id %> <br />

    The customer id is <%= Model.CustomerCode %> <br />

    <%if (Model.Amount > 100)
      {%>
    This is a priveleged customer.
    <% }
      else
      { %>
    This is a normal customer
    <%} %>

    </div>
</body>
</html>

And the customer controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvccustomer.Models;


namespace Mvccustomer.Controllers
{
    public class CustomerController : Controller
{
    //
    // GET: /Customer/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FillCustomer()
    {
        return View();
    }
    public ActionResult DisplayCustomer(Customer obj)
    {
        return View(obj);
    }

}

}

Let me know if I need to post any more elements of the project. When I build the Mvccustomer project it compiles fine with no errors. It's only the unit test that is giving me trouble. I imagine that this question is a bit convoluted and I eagerly await the learning experience that will come with all of the constructive criticism. Thank you.

Edited Controller and Unit Test that ultimately worked:

Customer Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvccustomer.Models;
using Mvccustomer.Controllers;

namespace Mvccustomer.Controllers
{
public class CustomerController : Controller
{
    //
    // GET: /Customer/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FillCustomer()
    {
        return View();
    }

    [HttpPost]
    public ActionResult DisplayCustomerView(CustomerModel customerModel)
    {
      var myView = View("DisplayCustomerView", customerModel);
      //myView.ViewName = "DisplayCustomer";
      return myView;
    }

}
}

Edited Unit Test:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mvccustomer.Models;
using Mvccustomer.Controllers;
using System.Web.Mvc;

namespace MvcUnitTest
{


[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void DisplayCustomer()
    {
      // instantiates new instance of CustomerController class
      CustomerController controller = new CustomerController();

      var customer = new CustomerModel();

      var customerViewActionResult = controller.DisplayCustomerView(customer);
      var customerViewViewResult = customerViewActionResult as ViewResult;


      Assert.AreEqual("DisplayCustomerView", customerViewViewResult.ViewName);

    }
}
}

You are testing for the view name that is supposed to be returned by the controller, but you didn't create a controller. Instead you are calling .DisplayCustomer() on the Customer not the CustomerController

I would also make your code a little more explanatory. Names of unit test functions should explain what they are testing. Variable names should explain what they are (obj is a bad name, because it is meaningless).

Consider reading another programmer's code and needing to understand how it works, or coming back to your own code 2 years from now and trying to remember how it worked. Giving things explanatory names helps. I would rewrite your test like this:

    [TestMethod]
    public void DisplayCustomer_ReturnsViewNamed_DisplayCustomer()
    {
        const string expectedViewName = "DisplayCustomer";
        var customer = new Customer();
        var controllerUnderTest = new CustomerController();

        var result = controllerUnderTest.DisplayCustomer(customer);

        Assert.AreEqual(expectedViewName, result.ViewName);
    }

If you like reading through programming books, I highly recommend Clean Code by Robert Martin. It is written with code examples in Java, but Java is syntactically close to C#, and it is a great book on keeping your code readable, simple and well organized. I keep a cheat-sheet of notes from the book that I ofter refer to when coding.


Edit:

Regarding your new error:

'System.Web.Mvc.ActionResult' does not contain a definition for 'ViewName' and no extension method 'ViewName' accepting a first argument of type 'System.Web.Mvc.ActionResult' could be found (are you missing a using directive or an assembly reference?)

The method signature on your controller is:

public ActionResult DisplayCustomer(Customer obj)

It returns an ActionResult object. The property .ViewName does not exist on this type, it is actually a property of ViewResult.

The line inside the DisplayCustomer() method in the controller returns:

return View(obj);

The View() method actually returns a ViewResult, but the ViewResult class extends ActionResult:

public class ViewResult : ActionResult

So it is OK that your method signature is set to ActionResult but you actually always return a ViewResult since ViewResult is an ActionResult. (Typical OO inheritance stuff, but hopefully this part makes sense so far).

In your test, when you call DisplayCustomer() as far as the test knows all it has to go by is the method signature, which is tellign the compiler that it will return an ActionResult. Therefore the compiler is trying to find a property names ViewName on the Actionresult class which does not exist.

There are 2 ways you can fix this:

One is to simply cast the result in your test:

var varresult = (ViewResult)obj.DisplayCustomer();

Or, since that method always returns a ViewResult you can change the method signature to indicate that it returns this more specific type:

public ViewResult DisplayCustomer(Customer obj)
{
    return View(obj);
}

From time to time, I want, as a safety check, to check that a variable v is not used in some portion of code, or in the remainder of some function, even though it is still visible in the scope of this function/portion of code. For instance:

int x;
// do something with x 
DEACTIVATE(x);
// a portion of code which should not use x
ACTIVATE(x);
// do something else with x

Is there a good way to perform that type of verification at compile time?

NOTE: I know that one should always use a scope that is as small as possible for each variable, but there are cases where pushing this practice to an extreme can become cumbersome, and such a tool would be useful.

Thanks!

The best way to achieve this is to actually have small scopes in your code, i.e. use short, focused methods which do one thing only. This way you tend to have few local variables per each individual method, and they go out of scope automatically once you don't need them.

If you have long legacy methods which make you worry about this problem, the best long-term solution is to refactor them by extracting smaller chunks of functionality into separate methods. Most modern IDEs have automated refactoring support which lowers the risk of introducing bugs with such changes - although the best is of course to have a proper set of unit tests to ensure you aren't breaking anything.

Recommended reading is Clean Code.

Hi I was just wondering how I can change the code below to less lines of code, it contains a lot of repeated lines,

basically what it does it swaps images and make them zoom in,

any help would be appreciated,

 // JavaScript Document
$(function() {

    var fullWidth = 1500; // Width in pixels of full-sized image
    var fullHeight = 2000; // Height in pixels of full-sized image
    var thumbnailWidth = 327;  // Width in pixels of thumbnail image
    var thumbnailHeight = 480;  // Height in pixels of thumbnail image

    // Set size of div
    $('.big_product').css({
                    'width': thumbnailWidth+'px',
                    'height': thumbnailHeight+'px'
    }); 

  //on page load hide small product2 and small product3
  $('#small_product2,#small_product3').hide();

  var selected_color;
  //get the selected color
  $('#colors option').click(function() {
      selected_color = $('#colors option:selected').text().toLowerCase();

      //show the relevant product according to selected color
      if(selected_color == 'navy') {              
          $('#small_product2,#small_product3').hide();
          $('#small_product1').show();
      }

     else if(selected_color == 'grey') {
          $('#small_product1,#small_product3').hide();
          $('#small_product2').show();
      }

      else if(selected_color == 'black') {
          $('#small_product1,#small_product2').hide();
          $('#small_product3').show();
      }
 });

//hide the full-sized(the largest) pictures
$('#full1-1,#full1-2,#full1-3').hide();

//hide the thumbnails
$('#thumbnail1-1,#thumbnail1-2,#thumbnail1-3').hide();

//when the first small pic is clicked
$('#small_product1-1').click(function() {
    $('#main_product,#big_product1-2,#big_product1-3').hide();
    $('#big_product1-1,#thumbnail1-1').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-1').click(function() {
    $('#thumbnail1-1').toggle();
    $('#full1-1').toggle();                 
});

// Do some calculations
    $('#big_product1-1').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-1').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });

//when the second small pic is clicked
$('#small_product1-2').click(function() {
    $('#main_product,#big_product1-1,#big_product1-3').hide();
    $('#big_product1-2,#thumbnail1-2').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-2').click(function() {
    $('#thumbnail1-2').toggle();
    $('#full1-2').toggle();                 
});

// Do some calculations
    $('#big_product1-2').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-2').css({
                        'left': '-' + posX + 'px',
                        'top': '-' + posY + 'px'
        });
  });

//when the third small pic is clicked
$('#small_product1-3').click(function() {
    $('#main_product,#big_product1-1,#big_product1-2').hide();
    $('#big_product1-3,#thumbnail1-3').show();
});

// Toggle full and thumbnail pictures on click
$('#big_product1-3').click(function() {
    $('#thumbnail1-3').toggle();
    $('#full1-3').toggle();                 
});

// Do some calculations
    $('#big_product1-3').mousemove(function(e) {
        var mouseX = (e.pageX-400) - $(this).attr('offsetLeft'); 
        var mouseY = (e.pageY-400) - $(this).attr('offsetTop'); 

        var posX = (Math.round((mouseX/thumbnailWidth)*100)/100) * (fullWidth-thumbnailWidth);
        var posY = (Math.round((mouseY/thumbnailHeight)*100)/100) * (fullHeight-thumbnailHeight);

        $('#full1-3').css({
            'left': '-' + posX + 'px',
            'top': '-' + posY + 'px'
        });
  });
});

I advice you to read clean code. It got allow of eye openers

How can I write a concise code in c#? I am sure this will lead to become a great programmer. Is thr any book that I can follow that teaches on writing neat and clean c# code?

Start with Clean Code by Uncle Bob. Great easy read. I consider it a must for any programmer in any language. It's not specific to C# but that's not really that important considering what the book can lead you to.

There are many others but I would start there. To complement, The Art of Unit Testing is a nice read as well and can get you far fast.

Good luck!

I am looking for feedback on my control architecture script (included below). Specifically, I am looking for feedback regarding the script's design, organization, commenting, and formatting. I enjoy php programming as a hobby, and am looking to learn where I can improve my code.

Thanks in advance!

class FrontController extends ActionController {

//Declaring variable(s)
private static $instance;
protected $controller;

//Class construct method
public function __construct() {}

//Starts new instance of this class with a singleton pattern
public static function getInstance() {
    if(!self::$instance) {
        self::$instance = new self();
    }
    return self::$instance;
}

public function dispatch($throwExceptions = false) {

    /* Checks for the GET variables $module and $action, and, if present,
     * strips them down with a regular expression function with a white
     * list of allowed characters, removing anything that is not a letter,
     * number, underscore or hyphen.
     */
    $regex  = '/[^-_A-z0-9]+/';
    $module = isset($_GET['module']) ? preg_replace($regex, '', $_GET['module']) : 'home';
    $action = isset($_GET['action']) ? preg_replace($regex, '', $_GET['action']) : 'frontpage';

    /* Generates Actions class filename (example: HomeActions) and path to
     * that class (example: home/HomeActions.php), checks if $file is a
     * valid file, and then, if so, requires that file.
     */
    $class = ucfirst($module) . 'Actions';
    $file  = $this->pageDir . '/' . $module . '/' . $class . '.php';

    try {

        //Checks for existance of file
        if (!is_file($file)) {
            throw new Exception('File not found!');
        }

        //Includes file
        require_once $file;

        /* Creates a new instance of the Actions class (example: $controller
         * = new HomeActions();), and passes the registry variable to the
         * ActionController class.
         */
        $controller = new $class();
        $controller->setRegistry($this->registry);

        //Trys the setModule method in the ActionController class
        $controller->setModule($module);

        /* The ActionController dispatchAction method checks if the method
         * exists, then runs the displayView function in the
         * ActionController class.
         */    
        $controller->dispatchAction($action);

    } catch(Exception $error) {

        /* An exception has occurred, and will be displayed if
         * $throwExceptions is set to true.
         */
        if($throwExceptions) {
            echo $error;
        }
    }
}
}

abstract class ActionController {

//Declaring variable(s)
protected $registry;
protected $module;
protected $registryItems = array();

//Class construct method
public function __construct(){}

public function setRegistry($registry) {

    //Sets the registry object
    $this->registry = $registry;

    /* Once the registry is loaded, the controller root directory path is
     * set from the registry.  This path is needed for the controller
     * classes to work properly.
     */
    $this->setPageDir();
}

//Sets the controller root directory from the value stored in the registry
public function setPageDir() {
    $this->pageDir = $this->registry->get('pageDir');
}

//Sets the module
public function setModule($module) {
    $this->module = $module;
}

//Gets the module
public function getModule() {
    return $this->module;
}

/* Checks for actionMethod in the Actions class (example: doFrontpage()
 * within home/HomeActions.php) with the method_exists function and, if
 * present, the actionMethod and displayView functions are executed.
 */  
public function dispatchAction($action) {
    $actionMethod = 'do' . ucfirst($action);
    if (!method_exists($this, $actionMethod)) {
        throw new Exception('Action not found!');
    }
    $this->$actionMethod();
    $this->displayView($action);
}

public function displayView($action) {
    if (!is_file($this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php')) {
        throw new Exception('View not found!');
    }

    //Sets $this->actionView to the path of the action View file
    $this->actionView = $this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php';

    //Sets path of the action View file into the registry
    $this->registry->set('actionView', $this->actionView);

    //Includes template file within which the action View file is included
    require_once $this->pageDir . '/default.tpl';
}
}

class Registry {

//Declaring variables
private $store;

//Class constructor
public function __construct() {}

//Sets registry variable
public function set($label, $object) {
    $this->store[$label] = $object;
}

//Gets registry variable    
public function get($label) {
    if(isset($this->store[$label])) {
        return $this->store[$label];
    } else {
        return false;          
    }
}

//Adds outside array of registry values to $this->store array
public function addRegistryArray($registryItems) {
    foreach ($registryItems as $key => $value) {
        $this->set($key, $value);
    }
}

//Returns registry array
public function getRegistryArray() {
    return $this->store;
}
}

Without having a detailed look on your code:

Try to write code that is self-explanatory by using meaningful function and variable names. Only use comments where the purpose or the functioning of your code is not clear. E.g.

//Declaring variable(s)
//Class construct method
//Checks for existance of file
//Includes file

are useless comments because the code itself is already clear enough.

A book worth reading: Clean Code

I am making a user profile update php file and I wonder, is there any other ways to simplify this if statement code that checks if input is empty or not? Currently code looks like this:

`

<?php 
    session_start();
    $name = test_input($_POST['name']);
    $surname = test_input($_POST['surname']);
    $password = $_POST['password'];
    $newPassword = $_POST['newPassword'];
    $newConfirmPassword = $_POST['newConfirmPassword'];

    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        $data = strtolower($data);
        return $data;
    };

    if($password != $_SESSION['password']){
        die('Wrong password, try again!');
    }else{
        if(empty($name) && empty($surname) && empty($newPassword) && empty($newConfirmPassword)){
            die('No changes has been made!');   
        }else if(!empty($name) && empty($surname) && empty($newPassword) && empty($newConfirmPassword)){
            //name update
        }else if(!empty($name) && !empty($surname) && empty($newPassword) && empty($newConfirmPassword)){
            //name and surname update
        }else if(!empty($name) && !empty($surname) && !empty($newPassword) && empty($newConfirmPassword)){
            die('New passwords do not match');
        }else if(!empty($name) && !empty($surname) && empty($newPassword) && !empty($newConfirmPassword)){ 
            die('New password do not match');
        }else if(!empty($name) && empty($surname) && !empty($newPassword) && !empty($newConfirmPassword)){
            //name and passwords update
        }else if(!empty($name) && !empty($surname) && !empty($newPassword) && !empty($newConfirmPassword)){
            //name , password and surname update
        }else if(empty($name) && !empty($surname) && empty($newPassword) && empty($newConfirmPassword)){
            //surname update
        }else if(empty($name) && !empty($surname) && !empty($newPassword) && empty($newConfirmPassword)){
            die('New passwords do not match');
        }else if(empty($name) && !empty($surname) && empty($newPassword) && !empty($newConfirmPassword)){
            die('New passwords do not match');
        }else if(empty($name) && !empty($surname) && !empty($newPassword) && !empty($newConfirmPassword)){
            //surname and password change
        }else if(empty($name) && empty($surname) && !empty($newPassword) && empty($newConfirmPassword)){
            die('New passwords do not match');
        }else if(empty($name) && empty($surname) && empty($newPassword) && !empty($newConfirmPassword)){
            die('New passwords do not match');
        }else if(empty($name) && empty($surname) && !empty($newPassword) && !empty($newConfirmPassword)){
            //password change
        };
    };
?>

`

Maybe there is a way to do this with function somehow?

I think John Slegers' answer is very good. It is the way how a program should work.

In my opinion it can be implemented even more "elegant" with exceptions. The advantage when using exceptions is, having nested functions, you do not have to check in each level the return value and pass it through - instead of this you can implement the final flow at only one point and it is well defined.

Think about spend around 33$ for this book Clean Code by Martin. There are some good ideas. You may not agree with all of them but it gives you really a good guideline how to program.

As John pointed out in his comment try to use multiple functions and give the functions very good names. Be happy you are not a programmer 30 years ago where you had 2 characters for your function and variables names...

It is a very good sign you asked this question because you were not "satisfied" with your version.

I'd like to start a discussion on the best resources for refactoring tips, with an eye towards Front-End JavaScript refactoring.

A friend whose opinion I respect suggests this book, though it uses examples in Java. I understand that the principles of OO refactoring should translate to another language.

Let's talk about refactoring in general and JS refactoring specifically.

Check out Martin's Clean Code for some inspiration. The examples are in Java but the ideas should translate to JavaScript as well.

In order to refactor properly, you'll need to test your code well as having proper tests in place is a prerequisite for it. Try finding testing tools that give you code coverage as this will be extremely valuable.

In case your code hasn't been tested yet you can think testing as a method of learning. You write tests to prove or disprove your assumptions about it. Once you are done and covered it adequately you should be able to refactor the code using various patterns provided.

As Ira mentioned having a tool to detect clones may be valuable. That's definitely one way to look at it.

I think that often having proper perspective is half the solution. If you can state your design in clear terms, you'll end up with better results. Try not to over-engineer it too much by applying every possible pattern you find. :)

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.

My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.

So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?

My code:

class RefData
{
    Matrix mX;
    Vector mV;


    int mA;
    bool mB;

    getX();

    setB();

    update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.

}

or,

class RefDataUpdater
{
   update(RefData*); // something like this ?
}

There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.

And the answer is it depends. It depends on what you are trying to accomplish in your design--and if you might have more than one data-object that exhibit similar behaviors.

First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.

So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.

All this being said, as Robert Martin points out in the book:

There are ways around this that are well known to experienced object-oriented designers: VISITOR, or dual-dispatch, for example. But these techniques carry costs of their own and generally return the structure to that of a procedural program.

Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.

I have a set of codes in my function with a lot of if-else loops but each doing a diffrent one

like

if(ddlname.SelectedIndex = 0)
{
//do this
}
else
{
//do this
}

if (txtprice.Text ="")
{
//do tis
}
else
{
//do this
}

my whole program looks clumsy and unnecessarily long because of this one. I have some 20 dropdownlists and ten textboxes. Is there way to make this as simple as 1 or 2 for loops ?

I am currently reading Clean Code by Robert C. Martin. According to his book, you should refactor your method into several smaller methods, doing exactly one thing. You should for example extract every do this into its own method.

As to your question, I don't think there is any way of achieving the same logic using for loops, unless you do the same for every call.

foreach (ctl in page.ctls)
{
  TextBox tempTextBox = ctl as TextBox;
  if (tempTextBox != null)
  {
    doTheSameForEveryTextBox(tempTextBox)
  }

  DropDownList tempDropDownList as DropDownList; // not sure if this is the right Type...
  if (tempDropDownList != null)
  {
    doTheSameForEveryTextBox(tempDropDownList)
  }
}

void doTheSameForEveryTextBox(TextBox tempTextBox)
{
  if (tempTextBox.Text == "")
  {
    //TODO: implement your code here
  }
}

void doTheSameForEveryDropDownList(DropDownList tempDropDownList)
{
  if (tempDropDownList.SelectedIndex == 0)
  {
    //TODO: implement your code here
  }
}

I have certain functionality encapsulated in classes which I use in another class. I think this is called composition.

class DoesSomething01
{
    public:
        DoesSomething01();
        void functionality01();
        void functionality02();
};

class DoesSomething02
{
    public:
        DoesSomething02();
        void functionality01();
        void functionality02();
};

class ClassA
{
    public:
        ClassA();

    private:
        DoesSomething01 *m_doesSomething01;
        DoesSomething02 *m_doesSomething02;
};

If I have now a ClassB which "knows" ClassA and have to use/execute functionality01 and/or functionality02 of classes DoesSomething01 and/or DoesSomething02 I see two possibilities:

a) Add methods like this to ClassA to provide ClassB direct access to DoesSomething01 and/or DoesSomething02:

DoesSomething01 *getDoesSomething01() { return *m_doesSomething01; }
DoesSomething02 *getDoesSomething02() { return *m_doesSomething02; }

ClassB could then do something like this:

m_classA->getDoesSomething01()->functionality01();

b) Add (in this case four) methods to ClassA which forwards the method calls to DoesSomething01 and DoesSomething02 like this:

void doesSomething01Functionality01() { m_doesSomething01->functionality01(); }
void doesSomething01Functionality02() { m_doesSomething01->functionality02(); }
void doesSomething02Functionality01() { m_doesSomething02->functionality01(); }
void doesSomething02Functionality02() { m_doesSomething02->functionality02(); }

Which option is better and why?

What are the advantages/disadvantages of each option?

First option can be considered a code smell. According to Robert C. Martin's 'Clean Code' it is "Transitive Navigation" and should be avoided. Quoting the author:

In general we don’t want a single module to know much about its collaborators. More specifically, if A collaborates with B, and B collaborates with C, we don’t want modules that use A to know about C. (For example, we don’t want a.getB().getC().doSomething();.)

Second option looks better. It is classical use of Facade pattern. And it is better, because it hides other functionalities of classes DoesSomthing01 and DoesSomthing02. Then you ve'got simplified view of it which is easier to use than 1st option.

Edit: there is also one more thing. You've got two classes which have the same functionalites and are aggregated by other class. You should consider using Stratey pattern here. The your code will look like this:

class DoesSomething 
{
    public:
        virtual void functionality01() = 0;
        virtual void functionality02() = 0;
}

class DoesSomething01 : DoesSomething 
{
    public:
        DoesSomething01();
        void functionality01();
        void functionality02();
};

class DoesSomething02 : DoesSomething 
{
    public:
        DoesSomething02();
        void functionality01();
        void functionality02();
};

class ClassA
{
    public:
        ClassA();
       DoesSomething* doesSomething();                         // Getter
       void doesSomething(DoesSomething* newDoesSomething);    // Setter
       // ...

    private:
        DoesSomething *m_doesSomething;
};

Then you will need only two method instead of four:

void doesFunctionality01() { m_doesSomething->functionality01(); }
void doesFunctionality02() { m_doesSomething->functionality02(); }

I have faced difficulties trying to return a result combined with the set of errors from function call.

I have started from the following approach

List<String> errors;
bool result = Obj.GetResult(out errors, int id);

The second step was to introduce new class

public class OperationResult
{
  public bool Result {get;set;}
  public List<string> Errors {get;set;}

}

But then the dirty code started to appear inside the GetResult method.

For example

public OperationResult GetResult(int id)
{
  if (id == 0)
  {
    return new OperationResult { Result = false, Errors = {"Error"}};
  }

  if (id < 400)
  {
    var result = new OperationResult { Result = false, Errors = {"Error"}};
    if (id >200)
       result.Errors.Add("Error");
    return result;
  }
}

Then I've started to worry not allowing result user to edit the result they get.

I have extracted interface from the OpearationResult class which was able only to read data.

Now I'm want to add result builder class...

And at this point I've started to thinking that I'm doing something wrong. Trying to reinvent the bicycle, or just creating problems out of the air.

Please give me an advice, how to handle all this stuff. I am also curious how this is handled in the functional programming languages. (I mean immutability)

This might be a time to start throwing exceptions. In his book Clean Code, Robert Martin talks about the confusion and lack of readable code when you do something like:

CustomResult result = myUser.CanLogOn();

Because it would appear from reading the code that CanLogOn should simply return a bool indicating if the user is allowed to log on, but now it's getting a custom result object that has error codes etc. This will cause you to further pollute your code with things like

if(result.Result)
   LogOn();

instead of

if(myUser.CanLogOn())
   LogOn();

or even better

myUser.LogOn() 

and let it decide if it can or not.

This is a simplified example, because I'd assume apart from a DB exception there isn't a lot of possible errors that can occur in a CanLogOn() method.

While you shouldn't use exceptions for normal flow, they are there, in part, to prevent this pattern of output values, and error codes on the return, and needing to know the difference between a return code of 200 and 402 and -134.

It will make your code cleaner, easier to read, and might prompt you to examine if you really need all those exceptions, and if so, is this method the best place to throw them from.

I have lengthy functions in VB.NET (VS2008) and I'd like to shrink them down. I know about the #region directives, but they don't work inside functions.

I was wondering if anyone knew of any plugins for visual studio 2008 that would allow me to fold if statements, loops and try catch statements. I've found a couple of plugins for Visual Studio 2005 but none for Visual Studio 2008.

You may want to read Martin Fowler's book called Refactoring: Improving the Design of Existing Code, as well as Code Complete: 2nd Edition.

refactoring bookcode complete book

If you're having functions and subroutines that long, it means there are larger complexity forces at work that need refactoring.

Update:

I just finished the book Clean Code by "Uncle" Bob Martin, and I have to say that it belongs right next to the other two in the 'Must Read' category.

Clean Code

I have many exception classes. F.e.: InvalidMethodParameterException, EntityNotFoundException etc. All have some code like xxx.yyy.zzz and a description literal. The question is: is there any best practices and techniques to organize the classes and its codes/literals. For now, the way I am doing is to put all codes and literals in other classes and even property files ((. It looks to me very frastrating, because to add one exception, i have to make another changes on other files, not one. And to throw the exception, I use a class with static methods, which throws them. These methods and approaches are not created by me, but where I work. So I would like to offer other more efficient approaches. For example, when I offered to use just simply store each exceptions literal and code inside own class, they just ignored saying it's unefficient and bad practice.

Any help would be appreciated!

I would argue that a system architecture which promotes developer efficiency will far outperform one which promotes execution efficiency, as the former can easily encompass the latter. If making a change to a single module requires you to open and modify multiple modules, the design is not promoting developer efficiency. My very favorite programming book recommends that exception types be motivated by exception handlers. Something like the following:

Version 1:
void tryToDoSomething(bool arg) {
    try {
        doSomething(arg); //Throws MyException
    } catch (MyException e) {
        if (e.errorMessage == "Try a different argument")
            tryToDoSomething(!arg);
        else if (e.errorMessage == "Try again")
            tryToDoSomething(arg);
    }
}
Version 2:
//Split the exception so that it can be handled differently
void tryToDoSomething(bool arg) {
    try {
        doSomething(arg); //Throws InvalidArgumentException, NotReadyException
    } catch (InvalidArgumentException e) {
        tryToDoSomething(!arg);
    } catch (NotReadyException e) {
        tryToDoSomething(arg);
    }
}

A modern compiler can optimize throws to make Version 2 significantly faster, besides being self documenting. This is why exceptions were actually created, as user defined types that the compiler could understand to replace the formerly obtuse error codes that had to be passed around and checked manually.

Anyway, if the error codes are designed to reach the user, I would argue that they are not exceptions but errors and should be thrown as such. You could probably design something like an ErrorFactory which would take a string error code and throw the correct derived type, or you could just throw directly. On the other hand, if the error codes do not reach the user, why bother using them?

I hear it a lot, and I have not seen a real definition.

I know it doesn't exist, except maybe in theory. But even in theory, what defines something as "Perfect code"?

You may want to read this book: http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Here are some quotes taken from the book itself:

Bjarne Stroustrup, inventor of C++ and author of The C++ Programming Language

I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.


Grady Booch, author of Object Oriented Analysis and Design with Applications Clean code is simple and direct.

Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.


“Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategy

Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.


Michael Feathers, author of Working Effectively with Legacy Code

I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you’re led back to where you are, sitting in appreciation of the code someone left for you—code left by someone who cares deeply about the craft.


Ron Jeffries, author of Extreme Programming Installed and Extreme Programming Adventures in C#

In recent years I begin, and nearly end, with Beck’s rules of simple code. In priority order, simple code:

  • Runs all the tests;

  • Contains no duplication;

  • Expresses all the design ideas that are in the system;

  • Minimizes the number of entities such as classes, methods, functions, and the like.

Of these, I focus mostly on duplication. When the same thing is done over and over, it’s a sign that there is an idea in our mind that is not well represented in the code. I try to figure out what it is. Then I try to express that idea more clearly.

Expressiveness to me includes meaningful names, and I am likely to change the names of things several times before I settle in. With modern coding tools such as Eclipse, renaming is quite inexpensive, so it doesn’t trouble me to change. Expressiveness goes The Total Cost of Owning a Mess 11 beyond names, however. I also look at whether an object or method is doing more than one thing. If it’s an object, it probably needs to be broken into two or more objects. If it’s a method, I will always use the Extract Method refactoring on it, resulting in one method that says more clearly what it does, and some submethods saying how it is done.

Duplication and expressiveness take me a very long way into what I consider clean code, and improving dirty code with just these two things in mind can make a huge difference. There is, however, one other thing that I’m aware of doing, which is a bit harder to explain.

After years of doing this work, it seems to me that all programs are made up of very similar elements. One example is “find things in a collection.” Whether we have a database of employee records, or a hash map of keys and values, or an array of items of some kind, we often find ourselves wanting a particular item from that collection. When I find that happening, I will often wrap the particular implementation in a more abstract method or class. That gives me a couple of interesting advantages.

I can implement the functionality now with something simple, say a hash map, but since now all the references to that search are covered by my little abstraction, I can change the implementation any time I want. I can go forward quickly while preserving my ability to change later.

In addition, the collection abstraction often calls my attention to what’s “really” going on, and keeps me from running down the path of implementing arbitrary collection behavior when all I really need is a few fairly simple ways of finding what I want.

Reduced duplication, high expressiveness, and early building of simple abstractions. That’s what makes clean code for me.


Ward Cunningham, inventor of Wiki, inventor of Fit, coinventor of eXtreme Programming. Motive force behind Design Patterns. Smalltalk and OO thought leader. The godfather of all those who care about code.

You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem.

I'm developing an open-source web application on top of Rails. I'd like to make my code as easy to understand and modify as possible. I'm test-driving my development with unit tests, so much of the code is "documented" through test cases (what each controller action expects as input, what instance variables are set for output, how helpers should be called, what business logic the models incorporate, etc.). And on top of that, Rails' conventions should make a lot of documentation unnecessary where my code conforms to them.

So, where's the balance between having a well-documented Rails application and trying to obey Don't Repeat Yourself? Are there any good blogs or articles with guidance on what (RDoc) documentation is really helpful in a Rails app, and what's just waste?

OK, not at all sure this is the right thing, but here's what I decided to do:

First, I thought that another Rails developer would be familiar with at least the intent of all of the code I wrote in the standard models, views, controllers directories. So, I started adding RDoc in other source files. It turns out that I'd built up a fair collection of code in lib/helpers and app/helpers, so started there. I wrote fairly typical function-level documentation for each helper method, focusing on intent and making sure I'd spelled out the things that the method and argument naming was mnemonic for. I didn't describe most of the corner cases, argument interactions, or error checking, leaving those details to a reading of each method's unit tests.

I found that while I was doing this, there were quite a few changes I made to method signatures, rather than having to document having done something stupid. (Have you read Clean Code by @unclebobmartin? I think it's great on all fronts, but especially on naming and self-documentation.) So, in addition to being an RDoc-adding exercise, I ended up spending a significant amount of time on (needed) refactorings--things that hadn't occurred to me in the refactoring pass after I'd first written the code because I didn't have enough distance yet. Perhaps 80% of the time I spent "adding RDoc" went into the code in my "helpers" directories, and the majority of that was refactoring rather than writing. So, even if nobody ever reads the RDoc itself, I think this was a valuable exercise and I'm very happy I spent the time

Next, I turned to my Controllers. I left the default single-line comments matching what scaffolding generates on each controller method as the first line of the RDoc (e.g., "# GET /"). For methods that do just the standard Rails thing, I didn't add any other documentation. I found that the unique things I'd done in my controller methods that were worth documenting had to do with what they return (e.g., data formats other than HTML), what they're for (actions beyond the standard REST model, like those intended to service Ajax requests), and whether they use a non-standard URL format. (This was really documentation of my route configuration, but since config/routes.rb isn't used to generate RDoc....) I didn't describe the behavior of my actions at all, feeling that my automated tests sufficiently covered all of the cases/behaviors someone would need to know. Finally, I added class-level comments mentioning the model class that the controller manipulates, not because people can't guess, but so that there'd be a convenient link in the generated HTML page.

Last, I worked on my models. Again, I didn't document behaviors (business logic), considering my unit tests to be sufficient here. What I did do was remind readers that field definitions are in db/schema.rb (felt silly, but if a developer new to Rails was trying to figure things out, being reminded of the base names for all the magic methods couldn't hurt). I also realized that lots of my models' behaviors were implemented through Rails' declarative helper methods called directly by the model classes (validates_..., belongs_to, etc.). Rather than trying to describe what this stuff accomplishes (after all, the desired model behavior is "described" by the tests), I just put in a reminder to look at the model source. (It's a shame RDoc isn't aware enough of Rails conventions to extract and document these things like it does Ruby constant definitions.)

And that was that. Perhaps a little more RDoc than I needed to write, but I think that it is light enough that it will get maintained as the code evolves, and it doesn't overlap at all with things "expressed" by my unit tests. Hopefully, it has filled the gap between what a Rails developer can infer from convention and what you're only going to figure out from the source. (Although I'm now noticing a growing impulse to pull more pieces from my views into helpers, even though they're not reused and it would mean losing ERB's inline HTML, just so that I can write descriptions for them. Go figure.)

Im doing a tutorial in Java and I always read that I must try not to be repetitive and I noticed this is very repetitive; So if anyone can give me some tips to make it less repetitive or somehow better it is much appriciated. Thanks ;) (This isn't part of the the tutorial, I made it just for fun because of what I am learning in science at school)

  1. Run.java file:

    package scientificFormula;
    
    public class Run {
    
        public static void main(String[] args) {
            Formula formula = new Formula();
    
            formula.compound1 = args[0];
            formula.compound2 = args[1];
    
            String theFormula = formula.createFormula();
            System.out.println("Molecule: " + args[0] + " " + args[1] + " = "
                    + theFormula);
        }
    
    }
    
  2. Formula.java file:

    package scientificFormula;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class Formula {
        String compound1;
        String compound2;
        static private Map<String, String> map = new HashMap<String, String>();
    
        static private void initiateIons() {
            // 1+
            map.put("Hydrogen", "H^1+");
            map.put("Lithium", "Li^1+");
            map.put("Sodium", "Na^1+");
            map.put("Potassium", "K^1+");
            map.put("Rubidium", "Rb^1+");
            // 2+
            map.put("Magnesium", "Mg^2+");
            map.put("Calcium", "Ca^2+");
            map.put("Strontium", "Sr^2+");
            // 3+
            map.put("Aluminium", "Al^3+");
            // 3-
            map.put("Nitrogem", "N^-3");
            map.put("Phosphorus", "P^-3");
            // 2-
            map.put("Oxygen", "O^-2");
            map.put("Sulfur", "S^-2");
            map.put("Selenium", "Se^-2");
            // 1-
            map.put("Fluorine", "F^-1");
            map.put("Chlorine", "Cl^-1");
            map.put("Bromine", "Br^-1");
            map.put("Iodine", "I^-1");
        }
    
        String createFormula() {
            initiateIons();
    
            // Example1: Input = Calcium Iodine:
            // 2x + -1y = 0
            // x = 1 and y = 2
            // Output = CaI2
            //
            // Example2: Input = Sulfur Iodine
            // Output = Molecule: Sulfur Iodine = SI2
    
            String symbol1 = map.get(compound1);
            String symbol2 = map.get(compound2);
    
            int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
                    symbol1.length() - 2));
            int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
                    symbol2.length() - 2));
    
            String letter1 = null;
            String letter2 = null;
    
            if (symbol1.length() == 5) {
                letter1 = symbol1.substring(0, 2);
            } else if (symbol1.length() == 4) {
                letter1 = symbol1.substring(0, 1);
            }
            if (symbol2.length() == 5) {
                letter2 = symbol2.substring(0, 2);
            } else if (symbol2.length() == 4) {
                letter2 = symbol2.substring(0, 1);
            }
    
            int possitive1 = (int) Math.sqrt(charge1 * charge1);
            int possitive2 = (int) Math.sqrt(charge2 * charge2);
    
            if ((possitive1 == 1) & (possitive2 == 1)) {
                return letter1 + letter2;
            } else if (possitive1 == 1) {
                return letter1 + possitive2 + letter2;
            } else if (possitive2 == 1) {
                return letter1 + letter2 + possitive1;
            }
            if (possitive1 == 0) {
                possitive1 = -(charge1);
            }
    
            if (possitive2 == 0) {
                possitive2 = -(charge2);
            }
    
            return letter1 + possitive2 + letter2 + possitive1;
        }
    }
    

I highly recommend reading the book clean code which mainly deals with refactoring.

Duplicating code is just one (important) issue when you start refactoring (also called DRY - Don't Repeat Yourself). There are many other principles and I'll try describe a few of them which I find most important:

One important "rule of thumb" is the SRP: Single Responsibility Principle, which says that each class should have only one responsibility, and if we apply the same idea to methods - each method should do only one thing! It might sound very strict, but when you'll start applying it - your code will become clearer to read and easier to maintain.

Another one is using meaningful names (classes/methods/variables):

return letter1 + possitive2 + letter2; // you probably meant positive with one 's' (typo!)

might mean something to you - but it will not mean much to another reader - now, of course you can solve it by adding code comments, but that's patching the problem instead of solving it. Further, code comments get stale - either become irrelevant or even worse - might mislead the reader when the code changes and the comment doesn't.

And last (for now), keep clear order of execution, let's take a piece of code that you posted and improve it:

    String symbol1 = map.get(compound1);
    String symbol2 = map.get(compound2);

    int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
            symbol1.length() - 2));
    int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
            symbol2.length() - 2));

    String letter1 = null;
    String letter2 = null;

    if (symbol1.length() == 5) {
        letter1 = symbol1.substring(0, 2);
    } else if (symbol1.length() == 4) {
        letter1 = symbol1.substring(0, 1);
    }
    if (symbol2.length() == 5) {
        letter2 = symbol2.substring(0, 2);
    } else if (symbol2.length() == 4) {
        letter2 = symbol2.substring(0, 1);
    }

    int possitive1 = (int) Math.sqrt(charge1 * charge1);
    int possitive2 = (int) Math.sqrt(charge2 * charge2);

As we can see: positive depends on charge which depends on symbol which depends on compound. And totaly unrelated to it: letter depends on symbol which depends on compound.

let's split it to separate methods:

int getPositive(String compound) { // I have no idea what "positive", "symbol" and compound represent, consider better names please
    String symbol = map.get(compound);
    int charge = Integer.parseInt(symbol.replace("+", "").substring(
                symbol.length() - 2));
    return (int) Math.sqrt(charge2 * charge2);
}

And now we can apply the same to getLetter(String compound) {...} etc.

I'm just starting learning Java after a few years of HTML/CSS coding so hopefully I'm not asking a old or stupid question here but any help explaining this problem would be very much appreciated.

I'm currently working through the Stanford CS106A online material and I've reached week 6, Assignment 2, Question 3 (http://see.stanford.edu/materials/icspmcs106a/13-assignment-2-simple-java.pdf).

As you can see it requires the placement of various objects on the screen to create the Graphics Hierarchy, as described. My plan was to use the centre coordinates to relatively place all the objects on the screen. However I've hit a problem that I can't seem to find an answer to. The course describes how Method Decomposition should allow each method to handle one problem (Single Responsibility Principle, I believe) so I have written the first part of my code as such:

//Import any libraries
import acm.program.*;
import acm.graphics.*;

    public class GraphicsHierarchy extends GraphicsProgram {

//Define constants
static final int BOX_WIDTH = 200;
static final int BOX_HEIGHT = 75;



public void run() {
    placeGRect();
}   

//Find centre x & y
double centre_x = getWidth() / 2; //check this
double centre_y = getHeight() * 0.5;//and this

//placeGRect method
public void placeGRect() {
    for (int count = 0; count < 4; count++) {
        GRect box = new GRect (BOX_WIDTH, BOX_HEIGHT);
        add(box);
        switch (count) {
        case 0:
            box.setLocation(centre_x, 75);
            break;
        case 1:
            box.setLocation((centre_x * 0.5), 250);
            break;
        case 2:
            box.setLocation(centre_x, 250);
            break;
        case 3:
            box.setLocation((centre_x * 1.5), 250);
            break;
        }
    }
}
}

However this doesn't work due to the centre_x & centre_y producing zero values. I discovered this by changing the program to a ConsoleProgram and having the getWidth & getHeight lines inside the run() method (and println their values on screen), which then produced the required values but didn't pass them to the GRect method (so still didn't work). However if I have the getWidth/getHeight lines listed out of the run() then they don't produce any values for relative positioning.

My question is given that each method should handle one task and (as much as possible) methods should be defined out of the run() method, then how I can I get the getWidth/getHeight values to the placeGRect() method without having one big block of code within the run() method. Which I understand is bad practise.

I'm not after any code to solve this, I really need to understand the principles of this so I can write effective code in the future. I prefer understanding to parrot-fashion code copying.

Thanks in advance for any help.

Very nice question! How to compose your methods is a matter of intuition rather than strict guidelines.

Certainly, methods should be focused on doing one thing and one thing only. Firstly, having short methods (even one-liners!) improves the understandability of the code. As a very rough example, think of this:

if (DateUtils.before(ticket.getExpirationDate(), new Date())) {
   accept(ticket);
}

and then this

if (isNotExpired(ticket)) {
   accept(ticket);
}

...

private boolean isNotExpired(Ticket t) {
   return DateUtils.before(t.getExpirationDate(), now());
}

private Date now() {
  return (new Date());
}

Pay attention to how the introduction of one line methods isNotExpired() and now() significantly improved your undestanding of what the code does.

Here's another example, this time that has to do with constructing objects:

Loan l1 = new Loan(15000, 36, f7.2, 2.5);
Loan l2 = new Loan(15000, 36, f7.2);

vs.

Loan l1 = Loan.newSubsidizedLoan(15000, 36, f7.2, 2.5);
Loan l2 = Loan.newNormalLoan(15000, 36, f7.2);

Note in this example how wrapping the constructors in two different methods significantly improves the documentation of code (without even needing to write comments);

If you are interested on the general topic of coding style, you should read this book.

Cheers

L.

I'm new to Cake, and to MVC's in general. I want to establish good habits from the get go. Among the good habits are keeping controllers lean, and making the models fat. But it's a bit of a moving target for a noob like me. If I need to pass info from one model to another, do I just dump all that into the controller? Try to make it work in a model?

Here's an action that is a prime example of the kind of confusion I'm trying to sort out.

Everything seems like it should be in the controller, but I'm likely wrong. This action gets a list of members, sends that to a view. In the view I can tick members whose accounts I want "activate." No ACL, just simple auth. I make sure that "sub-admins" only see the users they're allowed to manage by use of a db field, client_id. The two models I'm using are User and Client.

public function activate() {
    if ($this->request->is('get')) {
        $id = $this->Auth->user('id');
        $this->User->id = $id; //make sure current User is the logged in user
        $currentClient = $this->User->field('client_id'); // get client_id based on logged in user
        $members = $this->User->Client->find('first', array( // find users that have the same client_id
            'conditions' => array('id' => $currentClient),
            'recursive' => 1
        ));
        $this->set('clients', $members); // send the users to the view                  
    } else if ($this->request->is('post') || $this->request->is('put')) {
        $members = $this->request->data['Members']; // grab players submitted from push form
        $memberIds = array(); // this will hold the selected users
        foreach($members as $a){
            $memberIds[$a['id']] = $a['id']; // loop over user's that were selected
        }
        $usersToActivate = $this->User->find('all', array( //find user records, based on the array of id's
            'conditions' => array(
                "User.id" => $memberIds
            )
        ));
        $this->Ticket->bulkActivate($usersToActivate); // send array of members into model for processing
        $this->Session->setFlash('Activations sent.', 'default', array('class' => 'success'));
        $this->redirect(array('action' => 'index'));
    }
}

To my eye, it doesn't look drastically wrong... and I'm already doing some processing in the model (as seen with the bulkActivate that actually takes the user records, and generates activation tickets).

But I can't help but feel that it's not quite 100% yet.

I do not think you want to get only ONE client?

$members = $this->User->Client->find('first', array

I guess this should find all. I've improved this to use pagination in the case there are lots of users. I might be wrong with this but neither your associations nor the real goal is clear to me by looking at this code. I don't know how for example the Ticket model is associated with any other data. But I guess you're using Controller::uses, you should not do that but access related models through their associations.

Do not use horrible variable names like $a, that just sucks and nobody will ever know what that means in a larger code block or application. You also named an array containing client data $members, why not $clients? Read this: Clean Code and for CakePHP I suggest you to follow the CakePHP coding standards.

Describe the goal and this could be refactored even better I think. If you want to activate clients to have access to a ticket (thats what it looks like) why have you not done it in the ticket or client controller/model?

Also this huge amount of inline comments is just causing more mess than it helps. Write clean and readable code and the code will speak for itself. You have not done any super complex code or super complex math there. Again, I can just recomment you to read "Clean Code", it is in my opinion a "must read" for every developer.

<?php
    // UsersController.php
    public function activate() {
        if ($this->request->is('post') || $this->request->is('put')) {
            $this->User->activate($this->request->data);
            $this->Session->setFlash('Activations sent.', 'default', array('class' => 'success'));
            $this->redirect(array('action' => 'index'));
        }

        this->Paginator->settings['Client'] = array(
            'conditions' => array('id' => $this->Auth->('current_id')),
            'contain' => array(
                'OnlyModelsYouNeedHere'));
        $this->set('clients', $this->Paginator->paginate($this->User->Client)); 
    }
?>

<?php
    // User.php - the model
    public function activate($data) {
        $memberIds = array();
        foreach($data['Members']members as $member) {
            $memberIds[$member['id']] = $member['id'];
        }
        $usersToActivate = $this->find('all', array(
            'conditions' => array(
                'User.id' => $memberIds)));
        return $this->Ticket->bulkActivate($usersToActivate);
    }
?>

Passing the ids could be also trimmed down more, but hey, its late here now. :) Take this as a rough refactor of your code and think about what I have changed and more important why.

If you want to see proper examples of skinny controllers and fat models check our plugins out, the users plugins UsersController and Model might give you a bigger picture.

I'm studing how to build a mvc 3 web application and I am very confused. I spent the last few days reading about DDD, DI, IoC, TDD, EF (and tools like castle mapper, automapper, windsor, ecc) but I need your experience to make up my mind and choose a path to follow.

What I know:
- I want to use MVC 3.0
- I want to use EF 4.1 or 4.2
- I don't want to use Unit Tests for the moment but I want the structure of my project to support them in the future with few modification.
- I want to heavily use jQuery (the application need to be "very ajax")
- I obviously don't want my controllers and views to directly use EF objects
- I don't want to write duplicate code (ie: if I have a "person" db table with a "FirstName" property, I don't want to create a class for each layer of the software [dal, bll, ui, ...] with the same "person" data. Adding a field to the database should not need to add a property to way to many classes)

What I'd like to know:
- Which pattern(s) would you use?
- Best way of organizing projects inside the vs2010 solution?
- Code first or database first?
Last but not least: Is it possible to use all the cool features of mvc (data annotation, validation, ecc) with a heavily ajaxed site?

Of course I don't expect a fully detailed answer: I just need some pointers/help/link to go in the right direction and study what I need.

Thanks in advance.

To describe your situation: You want to use a couple of frameworks and want to use as much of the best practices/patterns out there. You will fail. Your job is to build working software and not to use as much patterns as possible for your job.

Some "high level advice":

  • DDD: don't do it! It does make sense in some projects but that often as people would think
  • TDD: go for it to improve your design
  • Patterns: When you have a solution for something or a design idea, check out if there is a pattern that describes that idea and not the other way round.
  • Avoid some patterns: Singleton, facade under some conditions,...
  • Take a look at SOLID and read Clean Code

I'm wondering if any experienced Java programmers could point out a few resources (can be websites, books, ebooks, videos, etc) that show a programmer good programming styles.

I look at my code and compare it to some example source online and mine just looks bloated, poorly formatted, and just not as readable as other's code. I know each programmer has their own style, but I would like to kick any bad programming habits that I've picked up. I would like my code to be read to an individual who has never touched the source before.

I know there are a lot of resources out there, but I don't know what the name of the topic is to be honest. (good programming structure? good programming conventions?)

I would like if there are some books I could pick up and read on the topic.

I appreciate any and all answers.

Clean Code is an excellent book.

In an MVC4 C# website, we are using Unit Testing to test our code. What we are currently doing is creating a mock database, then testing each layer:

  1. Test the Database - connecting, initializing, load, etc.
  2. Test the code accessing the database
  3. Test the view layer

I want these three categories to be run in order and only if the previous one passed. Is this the right way to go about it? The old way we were doing it was using a Dependency Injection framework was a weird approach to mock testing. We actually created a mock class for each data accessor, which sucks because we have to re implement the logic of each method, and it didn't really add any value because if we made a mistake with the logic the first time, we'll make it a second.

I want these three categories to be run in order and only if the previous one passed. Is this the right way to go about it?

No. You should be test everything in isolation and because of that any failing data access code should be completely unrelated to the view. So the view unit tests should fail for a completely different reason and because of that you should always run all tests.

In general, tests should run in isolation, and should not depend on any other tests. It seems to me that the view layer still depends on the data access code, but that you only abstracted the layer below. In that case, from the view's perspective, you are mocking an indirect dependency, which makes your unit tests more complex than strictly needed.

The old way we were doing it was using a Dependency Injection framework was a weird approach to mock testing

I'm not sure if I get this, but it seems as if you were using the DI container inside your unit tests. This is a absolute no-no. Don't clutter your tests with any DI framework. And there's no need to. Just design your classes around the dependency injection principle (expose all dependencies as constructor arguments) and in your test you just manually new up the class under test with fake dependencies -or- when this leads to repetitive code, create a factory method in your test class that creates a new instance of the class under test.

We actually created a mock class for each data accessor, which sucks

I'm not sure, but it sounds as if there's something wrong with your design here. You would normally have a IRepository<T> interface for which you would have multiple implementations, such as a UserRepository : IRepository<User>, and OrderRepository : IRepository<Order>. In your test suite, you will have one generic FakeRespository<T> or InMemoryRepository<T> and you're done. No need to mock many classes here.

Here are two great books you should definitely read:

  1. The Art of Unit Testing
  2. Dependency Injection in .NET

Those books will change your life. And since you'll be reading anyway, do read this book as well (not related to your question, but code be a life changer as well).

I need to create one of a number of different objects based on some value and I was advised to look into the Factory patterns. I do not want my client having to decide which object to create or to require hard-coded class names, so after doing some reading I came up with the following (simplified) example:

public class ObjectA : IObject 
{
}

public class ObjectA : IObject 
{
}

public interface IObjectFactory
{
    IObject CreateObject(ObjectCreationParameters p);
}

public abstract ObjectFactory : IObjectFactory
{
    abstract IObject CreateObject(ObjectCreationParameters p);
}

public ConcreteObjectFactory : ObjectFactory
{
    public IObject CreateObject(ObjectCreationParameters p)
    {
        IObject obj;
        switch (p.Value)
        {
            case A:
              obj = new ObjectA();
              break;
            case A:
              obj = new ObjectB()
              break;
        }
        return obj;
    }
}

The above works but I am a little confused as to whether my implementation is correct or not.

I would prefer not to have an ObjectAFactory and an ObjectBFactory as in a Factory Method pattern if it can be avoided, however, my object hierarchy does not seem to follow the same object hierarchy as in example of the Abstract Factory pattern. I do not have an ObjectA2 or ObjectB2 that would ever be created via a ConcreteObject2Factory.

Is my implementation correct or am I doing something wrong and if so, what?

Yes, it is a correct implementation. This switch statement may seem to be problematic and non-polymorphic but in fact, you can read about it in an excellent Code Clean book, rule G23: Prefer Polymorphism to If/Else or Switch/Case:

“ONE SWITCH” rule: There may be no more than one switch statement for a given type of selection. The cases in that switch statement must create polymorphic objects that take the place of other such switch statements in the rest of the system.

Your implementation abstracts creation of concrete object, co client don't have to worry about it and that is what this design pattern is for. Look also, for example, at Encapsulation section in the Wikipedia entry.

Is it generally considered bad practice to structure code with embedded expressions in method parameters? Should variables be declared instead?

(Android code snippet for an example)

((EditText)view.findViewById(R.id.fooEditText))
  .setText(
    someExpression
      ? getResources().getString(R.string.true_expression_text)
      : getResources().getString(R.string.false_expression_text)
  );

Personally I think it looks fine, but am just wondering if this is considered repulsing :)

I'd say this depends on the situation, for instance.

player.setName(User.getName());

Would be fine, however, train wrecking such as below...

player.setName(getGroup().getUsers().get(0).getName());

I'd say is bad practice and is mentioned in Clean Code by Bob Martin regarding the dangers of train wrecks. Also duplicate calls as mentioned by @Jon Skeet is another reason to use a variable rather than a method call.

I've seen several questions on SO asking about the best coding conventions for Java, such as here and here, but questions tend to focus on the most official Java coding conventions, rather than what the most used Java coding convention is. I think the most used style guide would be best to know as an individual programmer, but obviously how widespread a convention is should be balanced against how effective or up to date it is.

Can anyone tell me the most widely used code conventions for Java? Any references to quantitative evidence would be very helpful, but experience from working with others and an idea of what might become the standard in the future would be useful too. It would also be informative if any recommendation was balanced against the drawbacks of that style (e.g. the Oracle conventions no longer being updated).

I've assumed that it's best to follow a single guide so there's no confusion and anyone that joins on a project can just be given a link to the guide. This question is for programmers that are not part of a company with it's own style guide; it is for individual programmers that may work on collaborative projects where contributors should use the same style.

Edit: just to be clear, I am aware of the different style guides available. I'd like information from more experienced people as to which guidelines are most followed, and whether frequency of use is enough to justify using them, or whether they have other drawbacks that mean they should be ignored despite their popularity.

Which convention is more used is hard to say, and I dont think that you would get this information from anywhere. Even if you got it, would probabbly specific to a context or region.

My advice if you want something "official" and with a big name behind it, or a book, in the case that you need to justify this choice to someone else, I would say: Clean Code: A Handbook of Agile Software Craftsmanship.

There are a lot of people out there that follow the conventions of that book, and the book itself is writen with Java code examples. I think that's your best choice. :)

The Agile and Software Craftsmanship movement tend to follow someway or another much of the principles of that book (the later even more).

I was hoping you guys could help me on this one: how to handle errors and what to return? What I do, most of time, is make my functions/methods return two possible values. The intended value in case of success and FALSE in case of failure. This way I can use:

if(function()) { ... } else { ... }

I don't like to use exceptions because, generally, they print something and interrupt the functioning flow of the application. Of course, I can make them to return something and show an alert with the error. But it's too much work. And I don't like Pokemon so much to try to catch them all. (Awsum topic, btw)

Another thing I'm concerned about is to code something "error-handling" driven. As we know, users can do almost anything to cause an unexpected situation, and to code expecting these errors is too tiring and frankly, is making me paranoid. XD

I apologize for any english mispelling(I don't write too often). Thank you for reading this question. :D

PS: I read about defensive programming and the other questions but they don't quite answer my doubt.

You should consider using Exceptions. They don't print anything if you don't want to. At least this would be a better separation of your actual code and error handling.

You are right, having a function return a value or return false on error is not the best style (yes I know that this is probably done a lot).

If you want to learn more about good coding practice, I suggest to read Clean Code by Robert Martin.

So I have a fancy GUI in jQuery, which has gotten relatively complex. I would like to write tests for it, e.g. using assert(). However, it seems that writing such tests is difficult because GUIs don't manipulate data or make computations: they are just superficial interfaces to please the user.

So how does one generally write tests for GUIs?

assuming your code is fairly clean (modular and loosely coupled pieces of functionality that work together rather then a few uber functions), the first thing to do is choose a test framework. I recommend jasmine, because it fits the way I like to write tests, but if you are looking for more of an xUnit clone, qunit is also very well made.

If your code is not pulled apart (like 99.99% of javascript in the wild), I would first look at how to make jquery plugins, and extract as much as you can into them. Testing uber-functions that do loads of things is a scary proposition, but when you are talking about a module that does a single thing, testing gets much easier.

Finally, there is a bit of a learning curve with both how to structure complex javascript, and how to test it. Don't give up! Contrary to what some people would have you believe, javascript is very testable nowadays with very solid libraries and there are many people doing it (I just spent all day working on complex functionality, was practicing TDD the entire time, and it never felt clunky or unnatural)

Good luck, and feel free to ask for clarification if something here is unclear :)

EDIT:

By "pull apart" I mean move to a more modular approach rather then gigantic functions. In jQuery, the first step is with plugins, which will take you pretty far. If you are making a javascript "application", where most of your logic is in the front end and the back end is mostly for persistance, I would look at stuff like Backbone.js, which will help manage a very high level of complexity, but is totally overkill if you don't need it.

Going back to extracting plugins, try to find pieces of functionality that are sort of contained. I wrote a quick plugin today to remember the state of checkboxes in a table with paging, where the contents of the table get swapped out programmatically, but if a user checks a box on page one (but doesn't save), goes to page two, then back to page one they should still see that box checked.

If that checkbox code was inline in the paging code, it would make the paging code WAY more complicated. By pulling it into a plugin, it only complicates the paging code a little bit (calling $(table).saveCheckState() when a page unloads, and $(table).loadCheckState() when a new page loads) It also makes the testing very straightforward, all I need is a div with a few checkboxes to test the checkbox code, rather then needing to add more to the paging tests which are already pretty complex.

Not knowing your background or level of experience I would hesitantly recommend reading clean code if you want to learn more about this sort of stuff. Unfortunately is it java oriented rather then javascript, but most of it is universally applicable in any object oriented language (which javascript can be), and is probably the best intro level book into this topic. If you do full stack development (rather then just front end), have at least a working knowledge of java, are a junior/intermediate dev who wants to improve their craft, its one of those books everyone should read. If those things aren't true, it may end up just being confusing, or just not really be much use to you. So take the recommendation with a grain of salt :)

Can anyone summarize or bulleted list the types of things that go in each layer, and what layers are there in an MVC type design if you account for Dependency Injection?

I haven't found any clean diagrams that help me figure out where or try to go more in detail without writing an entire book.

I've been doing windows forms apps (including the sql server database design) for 3 years now as my sole function at work , with no one more experienced over me. I have been trying to break things apart into clean layers as much as I can figure my way through on my own based on presentation, business, database.

However based on reading the samples of Dependency Injection in .net it appears that the business logic should be the heart of the application with a separate layer that points to the specific database implementation. So then the ui goes in the presentation layer, controller just provides an abstraction/mapping layer to what the ui is allowed to do in the model layer, the business logic goes in the model layer, and the database/linq-to-sql goes in the database layer. Where everything can depend on the model layer, but it should depend on nothing.

To enable you to move the heart from X type to:

  • Windows forms
  • Asp.net
  • Asp.net MVC
  • Silverlight
  • Anything else

right? Would a 4 layer/project approach cover this type of thing? I suppose it would be 5 if you add a TDD layer.

I'm not averse to reading books, but I have plenty to read ( 3 at home, 1 at work, 3 ordered, 1 for college) already that are quite thick. Both of these approaches have resounding supporters but seem to conflict on overall design.

I think you're trying to understand too much at one time. For instance, a "TDD layer" makes no sense. DI and MVC are only tangentially related. DI does not specify what layer the business logic should be in.

Start simple. Work on one concept at a time. Test out your knowledge in one language before trying to apply it everywhere. You've got some great books on your reading list; work through some of them. The Art of Unit Testing will give you a basic understanding of TDD; it covers pragmatic uses of Dependency Injection as well, but doesn't go very deeply into it. The Extreme Programming series will cover TDD in more detail.

I'd suggest reading up on design patterns (don't start with the Gang of Four book - maybe Head First Design Patterns) and general design principles (Clean Code is a good start). Perhaps others can suggest references for learning about layered architecture.

Expect this to take a while. Expect to continue learning throughout your career.

Suppose I have this (outrageously) simplified XML schema:

<xsd:complexType name="Person">
  <xsd:sequence>
    <xsd:element ref="FirstName"/>
    <xsd:element ref="FamilyName"/>
  </xsd:sequence>
</xsd:complexType>

If I generate a Java class from it I get something like this:

public class Person {
  protected FirstName firstName;
  protected FamilyName familyName;

  // and the usual getters and setters
}

This class smells awfully like a Data Class and I'd like to add behavior to it. Extending it appears to me as the most obvious solution, but can I always count on such Java classes to be safely extensible? Will it always be safe to do?

A related question: how would you name the augmented class? Would you give it the same name as the original class but in another package? Would you call it something like MyPerson?

Independently from if the class was autogenerated or not: the smell is not awful but sweet. I'd never ever add behavior to a data class but create a/many separate class/es for behavior. The intention of this class is to provide the xml coded information as a java object. And the class shouldn't do anything else. That keeps the code clear and understandable.

You could rename the 'Person' class to 'FullPersonName' (or something else that describes the real content of the data class) and reserve the 'Person' class name for another class, that describes 'a Person' with 'a FullPersonName' (=composition).

Edit:

This might be controversial. Gene Garcia adds Data classes to his 'smells' list and suggests moving behavior into it. The Clean Code authors encourage the readers to keep the concern separated and to not create hybrid classes. Me, I like clean code.

There is a website (called the Anti-if campaign) that talks about how to replace big nested if-statements with something more maintainable (through the use of a 'bond class' see example). I understand the concept, but I don't know how to implement it (even with the example).

Question: May I get a concrete example of how to implement this (ie, the bond class)? - it has been bugging me for some time now. Java is my preference, but any examples are welcome.

note I have found one more article on this in stack overflow here

This special technique to avoid if-else-if constructs like shown in the example on that campaigns website can be found in in Clean Code by Robert C. Martin. If you follow his basic advices, you don't need to join the campaign ;)

The example at the referenced page looks dramatic mainly because the code is poorly formatted. This is how it should look like:

// Bond class
double calculateValue() {
  if(_type == BTP)  { 
    return calculateBTPValue();
  } else if(_type == BOT) { 
    return calculateBOTValue();    
  } else {
    return calculateEUBValue();
  }
}

The recommendation is to replace the condition with polymorphism, which isn't even the best ideas. A better design is to use composition:

public interface BondType {
  public double calculate();
}

public class BOT implements BondType { 
  //...
}

public class Bond {
  private BondType type;
  public Bond(BondType type) {
    this.type = type;
  }
  public doublce calculateValue() {
    return type.calculate();
  }
}

Here we got rid of the conditions and delegated the calculation to a new type class.

We are a few months into a green-field project to rework the Logic and Business layers of our product. By utilizing MEF (dependency injection) we have achieved high levels of code coverage and I believe that we have a pretty solid product. As we have been working through some of the more complex logic I have found it increasingly difficult to unit test.

We are utilizing the CompositionContainer to query for types required by these complex algorithms. My unit tests are sometimes difficult to follow due to the lengthy mock object setup process that must take place, just right, to allow for certain circumstances to be verified. My unit tests often take me longer to write than the code that I'm trying to test.

I realize this is not only an issue with dependency injection but with design as a whole. Is poor method design or lack of composition to blame for my overly complex tests? I've tried base classing tests, creating commonly used mock objects and ensuring that I utilize the container as much as possible to ease this issue but my tests always end up quite complex and hard to debug. What are some tips that you've seen to keep such tests concise, readable, and effective?

My subjective viewpoint:

  • MEF looks like a really nice plug-in framework; it's not designed to be a full-fledged DI framework. If you don't need the live swappable components, investigate full DI/IoC Container frameworks. Unity is Microsoft's alternative.
  • Make sure you are not doing the Service Locator anti-pattern. Use constructor injection of interfaces whenever possible. See this great post by Mark Seemann and this one by Jimmy Bogard. Your statement that you "utilize the container as much as possible" is a concern - few classes need to know anything about the container.
  • Get a really good mocking/isolation framework and learn to use it well. I love Moq. Try to do state verification on the system under test rather than behavior verification on the mock whenever possible.
  • Read The Art of Unit Testing. Read other books and articles on unit testing. Practice TDD. Keep learning.
  • Read Clean Code and insure that your classes follow the SOLID principles (especially the Single Responsibility Principle). Lengthy mock setup is a code smell; your classes are probably doing too much. High code coverage is nice, but a better metric might be cyclomatic complexity.
  • Don't worry about your unit tests taking longer to write than the production code. Treat your tests like production code, though, and remove duplication whenever you can preserve readability and maintainability.

What does Robert C Martin meant by saying

Output arguments are harder to understand than input arguments. When we read a function, we are used to the idea of information going in to the function through arguments and out through the return value. We don’t usually expect information to be going out through the arguments. So output arguments often cause us to do a double-take.

in his book 'The Clean Code' in chapter 3 Functions when he is talking about arguments in functions and which argument is he referring to here?

He means that we shouldn't have function that modifies input arguments. As an example (from "Clean Code"):

public void appendFooter(StringBuffer report)

He says report is rather output argument here because this function modifies it. Much better would be to have Report object and call:

report.appendFooter();

or instead of:

public void changeContactDetails(Person person)

do

person.changeContactDetails()

What is best practice for naming custom property in ExtJS? Is it a good idea to precede name with an underline?

Ext.create("Ext.Window,{
   height:50,
   _custom:"xxx",
   _action:"yyyy"
});

another idea is using data_ prefix to mimic html5 custom attribute convention.

I personally don't like anything in a variable name that carries additional syntactic information (Uncle Bob dedicates a whole section to this principle in http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882), not to mention the ugly code it produces (e.g. mywindow._custom).

I would just give your variables descriptive names, and then your code will read better and you shouldn't have to worry about collision with Ext properties (if you were worried about).

I like this much better:

Ext.create("Ext.Window,{
   height:50,
   customNameOfSomething:"xxx",
   actionToPerform:"yyyy"
});

What's in java the correct method to handle method params/inner errors?

All the three methods do the same thing, with a little difference in the second one where exception also have a "caused by" section.

Please not that in the third method, the return must be repeated every time i want to exit from it.

Consider also that exception handling is quite expensive in java (i've read this somewhere).

Thanks!!

public static String method(String arg) {
  block: {
    if (arg == null) {
      logger.error("arg is null");
      break block;
    }
    try {
      ...  
      return "ok";
    } catch (Exception e)
      logger.error("help!", e);
    }
  }
  return "ko";
}

public static String method(String arg) {
  try {
    if (arg == null) {
      throw new Exception("arg is null");
    }
    ...
    return "ok";
  } catch (Exception e) {
    logger.error("help!", e);
    return "ko";
  }
}

public static String method(String arg) {
  String result = "ko";
  if (arg == null) {
    logger.error("arg is null");
    return result;
  }
  try {
    ..
    result = "ok";
  } catch(Exception e) {
    logger.error("help!", e);
  }
  return result;
}

EDIT: Also, in the second method, you can differentiate inner method errors by using RuntimeException (or a custom one), bad idea?

You should use the one that is easiest to read. Remember that code is written once and read many times.

The third one is the most easiest to read.

Another rule which is pretty good. One entry one exist for every method. It is preferable to only use one return statement.

The reason is that it is easier for the next reader to understand what the thought is with the code.

More about this kinds of issue, you can read about in Clean Code http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Suggestion for one entry-exist solution:

public static String method(String arg) {
    String outString = "ko";
    try {
        if (arg != null) {
            outString = "ok";
        } else {
            logger.debug("arg is null");
        }
    } catch (Exception e) {
        logger.error("Help!", e);
    }
    return outString;
}

The heart of the method is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

From the Refactoring Home Page.

Keeping the system in a consistent and correct state is ensured by unit testing after each change.

Books

According to Clean Code, a function should take zero arguments when at all possible.

If we take a trivial example in Python with a function that does nothing more than add 2 to whatever is passed to it:

def add_two(x):
    return x + 2

>add_two(1)
3

The only way I can see that such a function can have zero arguments passed to it is by incorporating it into a class:

class Number(object):
    def __init__(self, x):
        self.x = x

    def add_two(self):
        return self.x + 2

>n = Number(1)
>n.add_two()
3

It hardly seems worth the effort. Is there another way of achieving the no-argument function in this example?

Aside from language-specific constructs, for someone who is programming in PHP, javascript, java, and python, what are the top 10 clean coding must-do's? I would like to keep my code as clean as possible and as readable as possible. For example, what's the take on placing the function body opening bracket on the same line as the function declaration vs a new line? Also, what's the take on spacing between things for example (x==10) vs ( x == 10 )? Any helpful hints for clean coding will be appreciated!

The answer in my opinion is that there is no real answer. A good rule is to stick to a convention, which usually is a reasonable convention that the community is already familiar with. I would rather suggest you a couple of books to have an idea.

For Java/C++/C#/VisualBasic you should read

Code Complete: a practical handbook of software construction

On the Java-heavy side, you would get useful insight from

Clean Code: a handbook of agile software craftmanship

Consider that the concepts in those two books are of general validity and should not be bound to a specific language.

As pointed out by this article, it is impossible to overload the comparison operator (==) such that both sides could take primitive types.

"No, the C++ language requires that your operator overloads take at least one operand of a "class type" or enumeration type. The C++ language will not let you define an operator all of whose operands / parameters are of primitive types." (parashift)

I was wondering:

**If I really-really needed to compare two primitives in a non-standard way using the ==, is there a way to implicitly cast them to some other class?

For example, the following code will work for const char* comparison, but it requires an explicit cast. I would prefer to avoid explicit casts if possible.

// With an explicit cast
if(string("a")=="A") // True

// Without the cast
if("a"=="A") // False

// An example overloaded function:
bool operator == (string a, const char* b)
{
    // Compares ignoring case
}

Casting can be pretty clunky in some situations, especially if you need to do several casts inside a long expression. So that's why I was looking for a way to automatically cast the first input (or both) to a sting type.


Edit 1:

Another way to do this is to write an isEqual(const char* a, const char* b) function, but I want to avoid this because it will result in a mess of parenthesis if I were to use it inside of a large if-statement. Here's an oversimplified example that still shows what I mean:

if (str1 == str2 || str1 == str3 || str2==str4)

As opposed to:

if (isEqual(str1,str2) || isEqual(str1,str3) || isEqual(str2,str4))


Edit 2:

I know there exist many ways to achieve the desired functionality without overloading the ==. But I looking specifically for a way to make the == work because I then could apply the knowledge to other operators as well.

This question is in fact closely related to the Wacky Math Calculator question I asked a few weeks ago, and being able to overload the == will help make the code look considerably nicer (visually, but perhaps not in a "clean code" way).

And that's I wanted to ask this question here on SO, in case someone had a cool C++ trick up their sleeve that I didn't know about. But if the answer is No then that's fine too.

You could certainly write one or more free functions to do your comparison. It doesn't have to be an operator overload.

for example:

bool IsEqual(const char* a, const string& b)
{
  // code
}

bool IsEqual(const string& a, const char* b)
{
  // code
}

and so on.

Does anyone know if there is a type of community based code standards and best practices web site\tool? Maybe similar to Stackoverflow where the community votes on the best practices. I've tried to build a full reference tool for my developers but it just turns into my own version of Clean Code or Effective Java. I've asked all my team members to read these books and similar ones for reference but I was just interested to see if there was a community based tool.

This site is a good place to start http://c2.com/cgi/wiki?JavaIdioms

First of all, Everything is kind of confusing. There is a few tutorials and complete documentation but i feel like something is just not working way it should. For now I'm a little bit confused and discouraged. I learned how to write forms, how to make views with blade. How to menage migrations and even seeds. I know how to create new controller and simple routes.

But guys... I need some advice if you would answer...

I created a form with a view for example that form:

{{Form::open(array('url' => 'person/confirm'))}}

{{Form::label('firstname', 'Firstname:')}}
{{Form::text('firstname')}}

{{Form::label('lastname', 'Lastname:')}}
{{Form::text('lastname')}}

{{Form::label('company_name', 'Company name:')}}
{{Form::text('company_name')}}

{{Form::label('mail', 'Mail:')}}
{{Form::text('mail')}}

{{Form::label('phone', 'Phone:')}}
{{Form::text('phone')}}

{{Form::label('additional_phone', 'Additional phone:')}}
{{Form::text('additional_phone')}}

{{Form::label('city', 'City:')}}
{{Form::text('city')}}

{{Form::label('postalcode', 'Postalcode:')}}
{{Form::text('postalcode')}}

{{Form::label('address', 'Address:')}}
{{Form::text('address')}}


{{Form::label('notes', 'Notes:')}}
{{Form::text('notes')}}


{{Form::submit('Submit')}}

{{Form::close()}}

Nothing fancy, just a basic form. If I call submit, it will take me to person/confirm route. And it will be like this:

Route::post('person/confirm', function(){

   $input = Input::all();

    DB::table('humanity')->insert(

       array('firstname' => $firstname);

    );

}

I know that it is wrong.

How to get values from $input?

How to insert it to table correctly and safely?

Where is the best place to make query call?

It will be better to make query before routing starts or when next route will execute?

It would be good to create query in controller function and execute it in route then redirect to "message: Success"?

What exactly are classes and models and how can I use them?

I plan to write some system and day by day it makes me more sicker than satisfied. Something call me that I had hitched my wagon to a star.

Thank you in advice.

It looks like you're in way over your head, especially since you asked what classes are.

I'd suggest putting Laravel (or any framework, for that matter) aside for a while until you have a solid understanding about object oriented programming and architectural patterns such as MVC / MVP. While Laravel resources will improve your knowledge quite a bit, it won't be nearly enough to create well structured applications.

Here are a couple of books that might be useful:

PHP Objects, Patterns and Practice

Clean Code: A Handbook of Agile Software Craftsmanship

Hi there I am quite new to java, however I need to plot a graph in JApplet. I have managed to declare all variables and classes, the equation is working (when compiled on it's own). but all I get is a strait line! can anyone tell me what am I doing wrong please?! in this applet the user will be asked to insert the values for abcd and the min and max values for the x axes

here is my code.......any help will be gratefully appreciated :)

package CubicEquationSolver;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;

public class graphApplet extends JApplet implements ActionListener {

    private static class g {
        public g() {
        }
    }

    int a;
    int b;
    int c;
    int d;

    int minimumX;
    int maximumX;
    int minimumY;
    int maximumY;

    int xCoOrdinates[];
    int yCoOrdinates[];

    int y;

    // Setting labels
    JLabel labelA = new JLabel("Enter value of A");
    JLabel labelB = new JLabel("Enter value of B");
    JLabel labelC = new JLabel("Enter value of C");
    JLabel labelD = new JLabel("Enter value of D");
    JLabel labelMinX = new JLabel("Minimum X value");
    JLabel labelMaxX = new JLabel("Maximum X value");
    JLabel message = new JLabel("Please insert your values");

    // Values will be entered here using JTextField
    JTextField textA = new JTextField();
    JTextField textB = new JTextField();
    JTextField textC = new JTextField();
    JTextField textD = new JTextField();
    JTextField minX = new JTextField();
    JTextField maxX = new JTextField();
    JTextField ref = new JTextField("Enter value 0-1");

    // declaring the layout for layout manager
    JPanel north = new JPanel();
    JPanel south = new JPanel();
    JPanel west = new JPanel();
    JPanel east = new JPanel();
    JPanel center = new JPanel();

    // declaring buttons using JButtons
    JButton calculate = new JButton("Calculate");
    JButton delete = new JButton("Delete");
    JButton refine = new JButton("Refine");

    // Calling from equation class
    // equation eq = new equation();

    private JPanel panel;
    private int width = center.getWidth();
    private int height = center.getHeight();

    @Override
    public void init() {
        // setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container c = this.getContentPane();
        this.setSize(900, 480);
        this.setVisible(true);

        // listener to buttons
        calculate.addActionListener(this);
        delete.addActionListener(this);
        refine.addActionListener(this);

        // listeer to user's input
        textA.addActionListener(this);
        textB.addActionListener(this);
        textC.addActionListener(this);
        textD.addActionListener(this);
        minX.addActionListener(this);
        maxX.addActionListener(this);
        ref.addActionListener(this);

        // assigning colours to panels to be distinguished
        north.setBackground(Color.LIGHT_GRAY);
        south.setBackground(Color.LIGHT_GRAY);
        west.setBackground(Color.YELLOW);
        east.setBackground(Color.GREEN);
        center.setBackground(Color.GRAY);

        // Declaring border
        BorderLayout layoutBorder = new BorderLayout();
        // setting up the grid (x rows, y clumns, space, space)
        GridLayout layoutGrid = new GridLayout(2, 8, 4, 4);

        // layout grid
        north.setLayout(layoutGrid);
        // set labels
        north.add(labelA);
        north.add(labelB);
        north.add(labelC);
        north.add(labelD);
        north.add(labelMinX);
        north.add(labelMaxX);
        north.add(ref);

        // calculate button
        north.add(calculate);
        // text boxes
        north.add(textA);
        north.add(textB);
        north.add(textC);
        north.add(textD);
        north.add(minX);
        north.add(maxX);
        north.add(refine);
        // delete button
        north.add(delete);

        south.add(message);

        // border layout
        c.add(north, BorderLayout.NORTH);
        c.add(south, BorderLayout.SOUTH);
        c.add(center, BorderLayout.CENTER);
        // c .add(west, BorderLayout.WEST);
        // c .add(east, BorderLayout.EAST);

        // panel = new JPanel();
        // panel.setPreferredSize(new Dimension(width, height));
        // panel.setBackground(Color.GRAY);
        // center.add(panel);

    }

    @Override
    public void actionPerformed(ActionEvent e) // throws NumberFormatException
    {
        // dafault message will be <message> -- "Please insert values"
        message.setText(e.getActionCommand());
        // when button "Delete" is pressed all values in text firlds will turn
        // null
        if (e.getActionCommand().equals("Delete")) {
            message.setForeground(Color.DARK_GRAY);

            textA.setText(null);
            textB.setText(null);
            textC.setText(null);
            textD.setText(null);
            minX.setText(null);
            maxX.setText(null);

            repaint();
        } else if (e.getActionCommand().equals("Calculate"))
            // when "Calculate" button is pressed, values will be attached to
            // equation
            try {
                message.setForeground(Color.DARK_GRAY);

                // -------------------------------------------------
                a = Integer.parseInt(textA.getText());
                b = Integer.parseInt(textB.getText());
                c = Integer.parseInt(textC.getText());
                d = Integer.parseInt(textD.getText());
                minimumX = Integer.parseInt(minX.getText());
                maximumX = Integer.parseInt(maxX.getText());

                System.out.println("center.getWidth() " + center.getWidth());
                System.out.println("center.getHeight() " + center.getHeight());
                System.out.println("minimum " + minX.getText());
                System.out.println("maximum " + maxX.getText());
                System.out.println("a " + textA.getText());
                System.out.println("b " + textB.getText());
                System.out.println("c " + textC.getText());
                System.out.println("d " + textD.getText());
                // ------------------------------------------------------

                message.setText("This is the result for " + "A "
                        + textA.getText() + ", B " + textB.getText() + ", C "
                        + textC.getText() + ", D " + textD.getText());
                draw();
            }

            catch (NumberFormatException ex)
            // if user inputs other than numbers, a warning message in the south
            // panel will show
            {
                message.setText("Please insert numerical value in "
                        + ex.getMessage());
                message.setForeground(Color.red);
                message.setFont(new Font("Tahoma", Font.BOLD, 12));
            }

        else if (e.getActionCommand().equals("Refine")) {
            // for refine
        }

    }

    // ===================================================================================

    private void calculation() {
        xCoOrdinates = new int[(maximumX - minimumX) + 1];
        yCoOrdinates = new int[(maximumX - minimumX) + 1];

        for (int i = 0; i < xCoOrdinates.length; i++)
        // for(int j = 0; j < yCoOrdinates.length; j++)

        {
            // generating the x co-ordinates and storing them in arrays
            xCoOrdinates[i] = minimumX + i;
            // generating the y co-ordinates using the formula given
            y = ((a * (int) Math.pow(i, 3)) + (b * (int) Math.pow(i, 2))
                    + (c * i) + (d));
            // storing y co-ordinates
            yCoOrdinates[i] = y;
            // displaying results
            // System.out.println("X = " + i + "   Y = " + getY());
            System.out.println("These are the values of X = " + i);
        }

        // printing the y axes values
        for (int i = 0; i < yCoOrdinates.length; i++) {

            System.out.println("this is the extracted Y " + yCoOrdinates[i]);

        }

        maximumX = xCoOrdinates[0];
        maximumX = xCoOrdinates[0];
        for (int i = 1; i < yCoOrdinates.length; i++) {
            if (yCoOrdinates[i] > maximumX)
                maximumX = xCoOrdinates[i];
            else if (yCoOrdinates[i] < minimumX)
                minimumX = xCoOrdinates[i];
        }

        System.out.println("MAXX is " + maximumX);
        System.out.println("MINX is " + minimumX);

        maximumY = yCoOrdinates[0];
        minimumY = yCoOrdinates[0];
        for (int i = 1; i < yCoOrdinates.length; i++) {
            if (yCoOrdinates[i] > maximumY)
                maximumY = yCoOrdinates[i];
            else if (yCoOrdinates[i] < minimumY)
                minimumY = yCoOrdinates[i];
        }
        System.out.println("MAXY is " + maximumY);
        System.out.println("MINY is " + minimumY);

    }

    // =================================================================================================

    public void draw() {
        Graphics g = center.getGraphics();
        g.setColor(Color.GRAY);
        g.fillRect(0, 0, center.getWidth(), center.getHeight());
        // g.fillRect(25,25, center.getWidth()-50, center.getHeight()-50);
        double x, y, nextX, nextY;
        int xPoint; // = 0;
        int yPoint; // = 0;
        int nextXpoint; // = 0;
        int nextYpoint; // = 0;

        g.setColor(Color.BLUE);

        for (xPoint = 0; xPoint <= (double) center.getWidth(); xPoint++) {
            x = scaleX(xPoint);
            y = equation(x);
            yPoint = scaleY(y);
            nextXpoint = xPoint + 1;
            nextX = scaleX(nextXpoint);
            nextY = equation(nextX);
            nextYpoint = scaleY(nextY);
            g.drawLine(xPoint, yPoint, nextXpoint, nextYpoint);
            // System.out.println("equation  --->" + eq.getY());
        }

    }

    private double equation(double x) {
        return y;
        // return a*x*x*x + b*x*x + c*x + d;
    }

    private double scaleX(int xPoint) {
        int minXstart = minimumX;
        int maxXend = maximumX;
        double xScale = (double) center.getWidth() / (maxXend - minXstart);
        return (xPoint - (center.getWidth() / 2)) / xScale;
    }

    private int scaleY(double y) {
        int minYstart = minimumY;
        int maxYend = maximumY;
        int yCoord;
        double yScale = (double) center.getHeight() / (maxYend - minYstart);
        yCoord = (int) (-y * yScale) + (int) (center.getHeight() / 2);
        return yCoord;
    }
}

Short term help: Check your output, do the values of x and y vary as expected? are they actually used during plotting? Use a debugger to step through your code. Then come back with a more focused questions.

Mid term (within the next two days): Please buy and read the following two books:

http://www.amazon.com/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1342369060&sr=1-1&keywords=clean+code

Classes as long as the one you posted are not acceptable, and make it next to impossible to understand the revlevant part. This is the reason why you received the down votes I'd guess.

I am looking for a way to display images on my ListField from a background thread. First in my drawListRow i try this

path = (String) imagePaths.elementAt(index);
bit = connectServerForImage(path);

g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);

but can't scroll smoothly throughout the list, and they say do not do networking or other blocking operations on the UI. But i also try this

private class imgConnection extends Thread
{      
        public imgConnection() {
                super();
        }

        public void run() {            

                try {
                    for (int i = 0; i < imagePaths.size(); i++)
                    {
                        final int index = i;                              
                        String path = imagePaths.elementAt(index).toString();
                        bit = connectServerForImage(path);
                        image.addElement(bit);

                    }
                }
                catch (Exception e)
                {
                    System.out.println(e.toString());                        
                }

                UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {        
                        _list.setSize(image.size());
                        subManager.add(_list);                        
                        screen.invalidate();
                        }  
                        });


        }
}

public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
    bit = (Bitmap) image.elementAt(index);
    g.drawBitmap(xText, y + yText, 80, 200, bit, 0, 0);
}

but nothing happens. Any idea, comments.


You are right, i just started java development 2 weeks ago particularly BB development and i try this link. I want to add a background thread to download image after i got the path url from json return.

first thread:

_connectionthread = new Connection();
_connectionthread.start();

private class Connection extends Thread
{
    public Connection()
    {
       super();
    }

    public void run() {      
        try {}
        catch (Exception e) {}
    } 
}

second thread:

_imgConnectionThread = new ImgConnection();
_imgConnectionThread.start();

private class ImgConnection extends Thread
{      
        public ImgConnection() {
           super();
        }

        public void run() {            
                try {
                }
                catch (Exception e)
                {
                }

        }
}

how to update images on ListField?

Answer is based on code from - pastebin.com/90UKTHzP

Terrible code! It's really hard to read and undersand! It looks like you copy pasted several examples from different locations. Also you overriding default behavior with same behavior. Also MainScreen already has VerticalManagerField. Also you're adding list every iteration to manager which will cause IAE. And main one thread is depended on result of second one. They start at the same time, but getting json from server and it's processing could take longer time, so image thread most probably will finish his run without any result.

So main recommendation to fix it - read clean code book! Read more about java development - conventions, multithreading. Read about BB development - UI api, networking.

And finally - start only one thread to get and parse json. After you get it finished - start another thread to get images.

There some minor things that could save you more battery and processor time also - start loading images on demand - when it painted or going to be painted (user scrolls list).

I am looking for some decent coding standards and best programming practices for C#?

The same would go for ASP.NET and ASP.NET MVC.

Check out this excelent coding guidlines for C# 3.0 and 4.0

http://csharpguidelines.codeplex.com/releases/view/46280

For best programming practices check out Clean Code

I am new to java and thanks to this site figured out how get the lowest value from the list but I am still struggling with how to get the same code to work for the highest value. I've been working on it for the past 2 hours. Again any help is appreciated

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class LargenSmall {
    public static void main(String[] args) throws IOException {
        String filename;        //Numbers file
        double lowest = Double.POSITIVE_INFINITY;//lowest number in list
        double highest; //highest number in list

        //Open the file
        File file = new File("Numbers.txt");
        Scanner inputFile = new Scanner(file);

        //Set lowest to zero


        //Read all the values in Numbers file and find the lowest value
        while (inputFile.hasNext()) {
            //Read the numbers in the file and compare each value to find lowest value
            double number = inputFile.nextDouble();
            if (number < lowest) lowest = number;
        }

        //Set highest to zero
        highest = 0.0;

        //Read all the values in Numbers file and find the highest value
        while (inputFile.hasNext()) {
            //Read the numbers in the file and compare each value to find highest value
            double number = inputFile.nextDouble();
            if (number > highest) highest = number;
        }

        //Close file
        inputFile.close();

        //Print out the lowest value in the list
        System.out.println("The lowest number in your file called, " +
                "Numbers.txt is " + lowest + ".");

        //Print out the highest value in the list
        System.out.println("The highest value in the list is " + highest);
    }
}

I have tried a few variations and highest value keeps coming back as 0.0

When learning the language (and after learning too) it helps to have small part of code, that is easy to write , test and maintain. For example comparing a number and remembering could moved to another class and tested.

I did not intend to correct your programming error. I would like to take a note on good programming practices to write better code .

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class LargenSmall {
    BigHolder bigHolder= new BigHolder();
    SmallHolder smallHolder = new SmallHolder();

    public static void main(String[] args) throws IOException {
        new LargenSmall().doSearch(args[0]);

    }
     void doSearch (String filename) throws IOException {
        //Open the file
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        iterateAndFetchNumbers(inputFile);
        inputFile.close();
        printResult();

         testNumbers();
     }

    private void iterateAndFetchNumbers(Scanner inputFile) {
        //Read all the values in Numbers file and find the highest value
        while (inputFile.hasNext()) {
            //Read the numbers in the file and compare each value to find highest value
            double number = inputFile.nextDouble();
            smallHolder.accept(number);
            bigHolder.accept(number);
        }
    }

    private void printResult() {
        //Print out the lowest value in the list
        System.out.println("The lowest number in your file called, " +
                "Numbers.txt is " + smallHolder.small + ".");

        //Print out the highest value in the list
        System.out.println("The highest value in the list is " + bigHolder.big);
    }
    //
    private static class SmallHolder {
        double small= Double.POSITIVE_INFINITY;
        public void accept(double newNumber) {
            if ( newNumber < small) {
                small = newNumber ;
            }
        }

    }

    private static class BigHolder {
        double big= 0;
        public void accept(double newNumber) {
            if ( newNumber > big ) {
                big = newNumber ;
            }
        }
    }

    //self test example - should be in junit class
    public void testNumbers() {
        BigHolder b = new BigHolder();

        b.accept(1);
        b.accept(3);
        b.accept(8);
        b.accept(0);
        b.accept(100);
        assert b.big == 0;//junit assert really
    }


}

I am revising code and I've seen a lot of methods in which we modify one of the input parameters and then return nothing. I'm wondering if this is the correct way to design these methods. For instance:

void addRespones (List<DTO> dtos, Set<String> codes){
     for (DTO dto: dtos){
          if (responses.contains(dto.getCode()){
               dto.setResponseOk(true);
          } else {
               dto.setResponseOK(false);
          }
     }
}

And then in the method calling addCodes we do some processing depending of the values of the responses.

Is this usage perfectly fine or is there any better common practice? It looks to me like we tend to use input parameters as "output" parameters too often. I thought that being OO, we should use some method of the class DTO, for instance

for (DTO dto: dtos){
     dto.setResponseOk(codes);
}

And then in class DTO:

boolean setResponseOk(Set<String> codes){
     if(codes.contains(this.getCode()){
          return true;
     }
     return false;
}

I thought that being OO, we should use some method of the class DTO

Well this depends on your codebase and what you are trying to do.

I am a big fan of Clean Code hence addResponse method would have gotten an axe in a code review.if one is "sure" that we have a finite list of response codes and no other condition ,variable or logic will take part in checking the validity of the response code.

I would have re-factored the class it like this.

void updateResponseCode(List<Dto> dtos,Set<String> responseCodes){
    for (DTO dto: dtos){
        dto.setResponseCodes(codes);
    }

}

And then in the DTO class :

// it always preferable to have a single point of exit for a method
boolean isResponseOk(){
    boolean responseOk=false;
    if(codes.contains(code){
        responseOk=true;
    }
    return responseOk;
}

Otherwise one will opt for a single method:

   void resolveResponseCode(List<Dto> dtos,Set<String> responseCode){
   for (DTO dto: dtos){
       if (responses.contains(dto.getCode()){
           dto.setResponseOk(true);
        } else {
           dto.setResponseOK(false);
        }
    }

}

Note that the only thing that has changed is the method name.

I am trying to learn exception handling for basic java programs. I read online and in a text book, and even practised the exercise my book gave me, yet I still don't have a good grasp of it.

I was hoping I could post my code below and see if anyone could tell me a better way to handle exceptions, or if I was even doing it properly.

public class labBookFortyTwo {

    public static void main(String[] args) {

        int size = 0;

        Scanner myInput = new Scanner(System.in);
        System.out.println("Please enter the amount of grades there are ");
        size = myInput.nextInt();

        double grade = 0;

        double[] myArray = new double[size];

        TestScoresTwo myScore = new TestScoresTwo(myArray, size);

        for (int count = 0; count < myArray.length; count++) {

            System.out.println("enter grade ");

            grade = myInput.nextDouble();

            myArray[count] = grade;

            System.out.println("you entered " + myArray[count]);

        }

        double avg = myScore.avgGrade();
        System.out.println("avg is \t " + avg);
    }

}

Here is my class:

public class TestScoresTwo {

    int size = 0;
    double[] tScore = new double[size];
    double sum = 0;

    public TestScoresTwo(double[] scores, int sizE) {
        // double[] tScore = scores; //this line messed me up
        // the below line works
        tScore = scores;
        size = sizE;
    }

    public double avgGrade() {

        try {
            for (int otherCount = 0; otherCount < size; otherCount++) {
                if (tScore[otherCount] < 0 || tScore[otherCount] > 100) {
                    throw new IllegalArgumentException("At the " 
                        + (otherCount + 1) + "   position "
                            + tScore[otherCount] + " is a wrong input ");
                }
            }

            for (int count = 0; count < tScore.length; count++) {
                sum = tScore[count] + sum;
            }

        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        double avg = sum / size;
        return avg;
    }
}

So far, one answer and one comment have told you that its "useless" or it "does not make sense" to throw and catch an exception "in the same place."

Here's what they're really trying to tell you: If a throw new FoobarException(...); is lexically enclosed within a try {...} catch (FoobarException ex) { ... } block, that's a sign that your code is poorly organized. It would be cleaner to move the code that does the throw into a separate method.

The excellent book, Clean Code:... by Robert C. Martin (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/) advocates for the Single Responsibility Principle---the idea that each method in a program should be responsible for doing just one thing.

He explicitly says that handling an exception is one thing. So, if you write a method that catches an exception, your code will be cleaner† if the corresponding throw happens in some other method that the first method calls.

private R reallyDoSomething(A a, B b, C c) throws SomeException {
    ...
    ... just worry about the normal case, and...
    if (something's not normal) {
        throw new SomeException(...);
    }
    ...
}

public R doSomething(A a, B b, C c) {
    try {
        return reallyDoSomething(a, b, c);
    } catch (SomeException ex) {
        ...
        ...handle abnormal case...
        ...
    }
}

Also, remember that there's a reason why they call them "exceptions": They should be exceptional (i.e., unusual). Usually, when a method throws an exception, it means that the method could not do whatever the job is that it is normally supposed to do.

Exceptions allow us to separate the code that handles the abnormal conditions from the code that does the normal work. That can make the normal case a lot easier to read. (If you've never tried to read a big C function definition where error-handling is intermingled with normal-case handling throughout, then you may not be able to fully appreciate the beauty of exceptions.)

So, if the purpose is to separate normal from abnormal, you can embrace that in two ways: (1) Put the handler for the abnormal case (the try/catch) in a separate method from the one that does the "normal" work, and (2) Don't use exceptions for "normal" things. (i.e., think twice before throwing an exception that is not an error).


† When Uncle Bob says "clean", he means "easy to read"

I am trying to make a bank account program, but I cannot figure out how to get all my variables visible to every class that I have, or how to make the withdrawal and deposit methods of my code visible. Can anyone look at my code and tell me what is wrong? I only want input and output in the client class.

Thanks

Client Class

public class Client {
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);       
    System.out.println("Enter your Name: ");
    String cusName = input.nextLine();
    System.out.println("Enter Account Type: ");
    String type = input.next();
    System.out.println("Enter Initial Balance: ");
    int bal = input.nextInt();
    BankAccount b1 = new BankAccount(cusName, num, type, bal);
    int menu;
    System.out.println("Menu");
    System.out.println("1. Deposit Amount");
    System.out.println("2. Withdraw Amount");
    System.out.println("3. Display Information");
    System.out.println("4. Exit");
    boolean quit = false;
    do {
      System.out.print("Please enter your choice: ");
      menu = input.nextInt();
      switch (menu) {
      case 1:
        b1.deposit();
        break;

      case 2:
        b1.withdraw();
        System.out.println("Current Account Balance=" + Balance);
        System.out.print("Enter withdrawal amount:");
        amount = input.nextInt();
        break;

      case 3:
        b1.display();
        break;

      case 4:
        quit = true;
        break;
      }
    } while (!quit);
  }
}

Money Class

public class Money
{

  static int accountNumber, Balance, amount;
  Scanner input = new Scanner(System.in);
  static String name, actype;
  public int deposit() {
    System.out.print("Enter depost amount:");
    amount = input.nextInt();
    if (amount < 0) {
      System.out.println("Invalid");
      return 1;
    }
    Balance = Balance + amount;
    return 0;
  }

  int withdraw()  {

    if (Balance < amount) {
      System.out.println("Not enough funds.");
      return 1;
    }
    if (amount < 0) {
      System.out.println("Invalid");
      return 1;
    }
    Balance = Balance - amount;
    return 0;
  }

}

BankAccount Class

class BankAccount {
  Scanner input = new Scanner(System.in);
  static String name, actype;
  static int bal, amt;
  Random randomGenerator = new Random();
  int accNo = randomGenerator.nextInt(100);

  BankAccount(String name, int accNo, String actype, int bal) {
    this.name = name;
    this.accNo = accNo;
    this.actype = actype;
    this.bal = bal;
  }
  void display() {
    System.out.println("Name:" + name);
    System.out.println("Account No:" + accNo);
    System.out.println("Balance:" + bal);

  }

  void dbal() {
    System.out.println("Balance:" + bal);
  }
}

I'm not going to answer this question for you. Instead, I'm going to recommend that you read a bit more about Java programming concepts that will explain it to you, by default.

If you don't want to read any of these links, @YogendraSingh answered this question really well, use that answer.

I am wondering what is the best way of checking potentially null method arguments.

First reasonable approach is with guava:

String validatedValue= Optional.fromNullable(input).or("defaultValue");

Second reasonable approach is with regular java. It might have advantage of being easy to understand for someone who does not know guava. However it still shows "low-level" code.

String validatedValue= input !=null ? input : "empty";

Or third approach. On the one hand looks nice in main method. On the other it potentially spawns a lot of small private methods.

String validatedValue = getValidatedValue(input); //this private method will contain option two

For now it seems that second or third approach is better and Optional should not be used in this case. Could someone tell what is best practice in this case?

Although I would not call this "validation", the preferred method for supplying deafult if null is similar to #2 (if not #2 itself) - using Guava's Objects.firstNonNull (since Guava 18 it's placed in MoreObjects):

String value = Objects.firstNonNull(input, "empty"); // MoreObjects since 18.0

which internally does:

return first != null ? first : checkNotNull(second);

With static import it's just:

String nonNullValue = firstNonNull(input, "empty");

but which one will you use is just a matter of preference.

P.S. I'd use Optional only in one case - if you want lazy evaluated default, but with strings it isn't a case. Private method only for null check is overkill, but if you have other assumptions about value, it's generally considered a good practice to use small private methods with meaningful names for this (see Clean Code by Uncle Bob).

I'd like to improve my coding skills and use the best programming approach to be a better programmer. Will someone recommend any website / platform for finding a code reviewer for checking and improving my code?

In addition, I would suggest that you read available good books that will help you write maintainable code. To start with, you may refer Clean Code, Refactoring for Software Desing Smells, and Refactoring: Improving the Design of Existing Code.

I have a function like this:

func_seo.php

<?php
function seo_title($s) {
    $c = array (' ');
    $d = array ('-','/','\\',',','.','#',':',';','\'','"','[',']','{','}',')','(','|','`','~','!','@','%','$','^','&','*','=','?','+');

    $s = str_replace($d, '', $s); 

    $s = strtolower(str_replace($c, '-', $s)); 
return $s;

}
?>

I want to use the function in App::Model.

I create like this, but it doesn't work:

<?php
class MyModel extends AppModel{
    var $name = 'MyModel';
    public function beforeSave(){
        $this->element('func_seo'); //Function Element View/Elements/func_seo.php
        $this->data['MyModel']['name_seo'] = seo_title($this->data['MyModel']['tutorial_name']);
        return true; 
    }
}
?>

This code should go into a Helper as it formats the output. This will also make sure the code can be easy reused between projects. Best would be to put it into something like an Utils plugin and share that as a git submodule between the apps.

If you want to store the changed data persistent to the DB make it a behaviour instead.

Your example code is wrong because it is a violation of the MVC pattern as you try to render an element in a model which is wrong.

Your variable naming is bad. $a + $b = $c. Hey, did you know that I meant to calculate a date by this? No. always give variables meaningful names. Check the coding conventions and follow them as well. Clean code is a good read as well.

Also pay attention to the scope keywords, don't mix var with public / protected / private. If you don't know what they mean check this page.

I have a java class, which has lots of functions, and all are in one file. The total number of lines in this file is around 50K. I makes it very hard to read. Can I move some of the functions to different file? If yes, how to do that. And if no, is there is some other technique to make program more readable.

Define domain objects (e.g. value objects) for the various concepts in your model, and put functionality related to those classes inside them.

For instance if you have

public class MyBigClass {
   ...
   private String account;
   ...
   private boolean accountIsValid() { ... }
   ...
}

then separate the account into an Account class, like this:

public class Account {
  public Account(String accountNumber) { ... }
  public boolean isValid() { ... }
}

public class MyBigClass
  ...
  private Account account;
  ...
}

if you keep doing that, and you make sure functionality is always located together with the value, your huge class will shrink rapidly. Try to avoid using native types (like String) for anything but the internal values of your value objects.

Also, look at libraries like commons-lang and google guava, to make sure you are not re-implementing something complex that there already exists a suitable solution for; Examples of classes that will both simplify your code and reduce the chance of implementation errors are EqualsBuilder and HashCodeBuilder.

To further improve your coding style, consider reading the following books:

I have a page that display list of Categories and also have a search box to search categories. The list of categories uses paging.

View Contains following Code:

@model PagedList.IPagedList<MvcWebsite.Models.User.ListOfCategories>
@using PagedList.Mvc;

foreach (var item in Model)
{
....
}

Model contains following code:

namespace MvcWebsite.Models.User
{    
    public class ListOfCategories

    {
        public int lngCatId { get; set; }
        public Byte intStatus { get; set; }
        public string txtTitle { get; set; }

        public ListOfCategories()
        {
            intStatus = 1;
        }
    }

    public class SearchBox
    {
        public string txtSearch { get; set; }
    }


public class UserViewModel
{
    public ListOfCategories ListOfCategories { get; set; }
    public SearchBox SearchBox { get; set; }
}
}

In my view if I change MvcWebsite.Models.User.CategoriesList to MvcWebsite.Models.User.UserViewModel I get error.

What do I need to do so paging and search box both work in page?

There a few problems with your code even with your preliminary version (with ListOfCategories used as a view model).

  1. You try to iterate through ListOfCategories whereas this class does not implement IEnumerable interface
  2. You use a naming convention ListOfCategories, but in fact you class represents a single Category.
  3. You want to change the view model to MvcWebsite.Models.User.UserViewModel but you do not change your view code.
  4. You use inappropriate naming conventions (please read the Clean Code book)
  5. You should not represent your Status by byte, it is better to use enum type to make it readable.

All in all your code should probably look like this:

public enum StatusType
{
    BasicStatus = 1,
    OtherStatus = 2,
    YetAnotherStatus = 3
}

public class Category
{
    public int CategoryId { get; set; }
    public StatusType Status { get; set; }
    public string Title { get; set; }

    public Category()
    {
        Status = StatusType.BasicStatus;
    }
}

public class SearchBox
{
    public string SearchText { get; set; }
}

public class UserViewModel
{
    public List<Category> Categories { get; set; }
    public SearchBox SearchBox { get; set; }
}

And your view:

@model PagedList.IPagedList<MvcWebsite.Models.User.UserViewModel>
@using PagedList.Mvc;

foreach (var item in Model.Categories)
{
....
}

And of course you should change the @model in your view code to comply with the changes:

@model MvcWebsite.Models.User.UserViewModel

I have some methods in a class which get called by only one method in the same class. Where is the best practice to put such methods? Private at the end of the class? Comming from gcc's C implementation I would define those helper methods in the method they are needed for, but that doesn't seem to work in C#.

In Bob Martin's excellent book Clean Code, there is a chapter on vertical formatting, with a section titled "The Newspaper Metaphor". I'll post an excerpt (emphasis mine):

Think of a well-written newspaper article. You read it vertically. At the top you expect a headline that will tell you what the story is about and allows you to decide whether it is something you want to read. The first paragraph gives you a synopsis of the whole story, hiding all the details while giving you the broad-brush concepts. As you continue downward, the details increase until you have all the dates, names, quotes, claims, and other minutia.

We would like a source file to be like a newspaper article. The name should be simple but explanatory. The name, by itself, should be sufficient to tell us whether we are in the right module or not. The topmost parts of the source file should provide the high-level concepts and algorithms.

Detail should increase as we move downward, until at the end we find the lowest level functions and details in the source file.

And a few pages ahead:

If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible. This gives the program a natural flow. If the convention is followed reliably, readers will be able to trust that function definitions will follow shortly after their use.

(...) [T]he topmost function calls those below it and (...) they in turn call those below them. This makes it easy to find the called functions and greatly enhances the readability of the whole module.

Besides this specific topic, the book contains a ton of other very, very useful well-funded information about these sometimes neglected aspects of code construction.

I have written the following code. It all works ok. However, I have been told that it is written in the incorrect format. I am not exactly sure what the correct way of coding this would be. Any help would or direction be much appreciated.

package com.mygdx.gameworld;

import com.badlogic.gdx.Gdx;
import com.mygdx.gameobjects.Egg;
import com.mygdx.gameobjects.Ground;
import com.mygdx.gameobjects.Hero;

public class GameWorld {

Hero hero = new Hero(); //This seems to the bit that causes some amusement.
Egg egg = new Egg(); //This seems to the bit that causes some amusement.
Ground ground = new Ground(); //This seems to the bit that causes some amusement.


public void update(float delta) {
    Gdx.app.log("GameWorld", "update");
    egg.update(delta);
    hero.update(delta);
    ground.update(delta);

}

public Hero getHero() {
    return hero;
}

public Egg getEgg() {
    return egg;
}

public Ground getGround() {
    return ground;
}

}

The code is basically ok, but a few changes should be made:

  1. Formatting (Ctrl+Shift+F in Eclipse, Alt+Shift+F in Netbeans).
  2. Since you have getters, all fields should be private (otherwise they are visible in com.mygdx.gameworld package).
  3. In my opinion it would be a little bit cleaner to move hero, egg, ground instantiation to the constructor.
  4. Your fields/methods should not contain any comments unless there is some very complicated logic in it. Try to treat your code as a documentation.

I really recommend: Clean Code by Robert C. Martin

I just want to know is it good practice to call multiple methods inside each other? say something like following :

public constructor()
{
  method1();
}

private method1()
{
 //processing data 
 //during process call method2()
}

Yes, decomposing code into multiple methods and calling them is a good thing.

It is a basic way of structuring code so it is simple to read and understand.

I suggest you pick up a copy of Clean Code.

Imagine a condintion should be true for a method to do its stuff. Which block represents the best approach (performance related and readability), or if not what is your suggestion?!

private void method()
{
    if(!condition)
    {
     MessageBox.Show("ERROR!");
     return;
    }     
    else
    {
        //DO STUFF
    }
}

OR

private void method()
{
    if(condition)
    {
         //DO STUFF
    }     
    else
    {
         MessageBox.Show("ERROR!");
         return;
    }
}

This is more of a style question than a "logical" question. Both of these approaches work, and which one you will use generally depends on your style as a thinker/developer.

That said, once you start using either one of these styles, it generally pays to be consistent. Having large classes where some functions do it the first way and others the second way can lead to maintainability concerns later.

Robert Martin's Clean Code presents an interesting chapter on functions that suggests, whichever way you choose, the //DO STUFF part should be another function call

Functions Should Only Do One Thing

I´m trying to create a application which print data in columns. My problem is that the job.setPrintable runs multiple times... This means that the document becomes totaly wrong...

Does anyone have some ideas about this?

Maybe you have some other ideas of how I can make this code better(?)...

Thank you in advanced

I do have for example 10 indexes in my ArrayList... When I run the application, it will create 20 columns in my document... 10 of them is totaly empty and do just take up space...

private final int PAGE_WIDTH = Math.round(MediaSize.ISO.A4.getX(MediaSize.MM));
private final int PAGE_HEIGHT = Math.round(MediaSize.ISO.A4.getY(MediaSize.MM) / 8);
private PrinterJob job = PrinterJob.getPrinterJob();
private Graphics2D column;
private Font font = new Font("Serif", Font.BOLD, 9);

private int writeOnRow = 0;
private int pageRow = 0;
private int columnSpace = 4;
private int itemsInRow = 3;
private int itemCurrentRow = 0;

public Printer(final ArrayList<Customers> resultAsList) {
    resultAsList.remove(0);

    job.setPrintable(new Printable() {
        public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
            if (pageIndex > 0) { 
                return NO_SUCH_PAGE;
            }

            column = (Graphics2D)g;
            column.translate(pf.getImageableX(), pf.getImageableY());

            column.setFont(font);

            for (Customers c : resultAsList) {
                String line =
                        c.getName() + "\n" +
                                c.getAddress() + "\n" +
                                c.getPostcode() + " " + c.getCity();

                //DATA, COLUMN, ROW
                column.drawString(c.getName(), columnSpace, writeOnRow += column.getFontMetrics().getHeight() + 2);
                column.drawString(c.getAddress(), columnSpace, writeOnRow += column.getFontMetrics().getHeight() + 2);
                column.drawString(c.getPostcode() + " " + c.getCity(), columnSpace, writeOnRow += column.getFontMetrics().getHeight() + 2);


                if (itemCurrentRow == itemsInRow) {
                    pageRow += PAGE_HEIGHT;
                    itemCurrentRow = 0;
                    columnSpace = 4;
                    itemCurrentRow++;
                } else {
                    writeOnRow = pageRow;
                    columnSpace += PAGE_WIDTH;
                    itemCurrentRow++;
                }

                writeOnRow += pageRow;
                laps++;

            }
            return PAGE_EXISTS;
        }
    });

    boolean doPrint = job.printDialog();

    if (doPrint) {
        try {
            job.print();
        } catch (PrinterException ex) {
            System.out.println(ex);
        }
    }
}

Your code does not look clean. Sooner or later it will be very hard to maintain - actually it already is.

  • It's cool that you've used all those integer values as fields, but it would be better if you make it constants i.e. private static final fields.
  • Avoid creating methods that take as much as 3 arguments. It is a sign that it could be divided into smaller pieces like methods, classes, etc.
  • Avoid using magic numbers like columnSpace = 4;. What is this 4? Consider making it a const field.
  • You don't swallow exceptions like you did. It doesn't make sense. Either you handle them or declare throws.

It seems that your loop may be invalid. For making your code more pretty I recommend you read Clean Code. It will make things much more clear.

In CakePHP I am trying to pass a simple parameter to my controller class method. However it looks like the parameter has to be visible in the URL. Can't I pass a parameter without it being visible in the URL?

My routing:

Router::connect(
    '/',
    array(
        'controller' => 'Pages',
        'action' => 'display'
    ),
    array(
        'pass' => array(
            'pageName' =>'home'
        )
    )
);

And my Controller method:

public function display($p_sPageName=null) {
Router::connect(
    '/',
    array(
        'controller' => 'Pages',
        'action' => 'display',
        'home',
    ),
);

This should be a default route in a baked application and already present. The book has also a very good section explaining the routing.

Also follow the CakePHP coding standard, this variable name $p_sPageName is bad. Nobody ever knows what $p_s means. This is a very good read about writing clean and readable code.

/**
 * Displays a static page
 *
 * @param string $pageName
 * @return void
 */
    public function display($pageName = null) { /*...*/ }

The doc block should tell you by "@param string $pageName" that it is a string not the variable name. Without documentation this becomes unreadable for everyone who does not know the naming conventions.

In MVC theory, the Model is the business domain class. For instance, we can have a Person class:

public class Person
{
    public int Id { get; set; } 
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In ASP.NET MVC, a ViewModel class is often used. This class can be tailored to suit a specific View:

public class PersonViewModel 
{
    public int Id { get; set; } 
    public string Name { get; set; }
    public bool Deactivate { get; set; }
}

In this example, FirstName and LastName will be combined in one string (Name), and there will also be a "Deactivate" checkbox on the form which will cause deactivation of the person.

In Controller, we populate the PersonViewModel object from the Person object. But, on the very first line of the View, we declare that the Model for this View is PersonViewModel.

@model PersonViewModel

Isn't the Model actually the class that is bound to the View (at least as far as ASP.NET MVC is concerned)?

If my Model is actually the PersonViewModel class, can I call this class just PersonModel? Or is this wrong and misleading?

In my opinion, this is easier to write (and read), and it would also be easier to explain to developers just starting with ASP.NET MVC. Isn't it better to leave out the ViewModel term completely, which can be confused with the ViewModel in the MVVM pattern?

I think that there is no good answer for this question. Both of the names you provided are self explanatory and could be used.

As Robert C. Martin writes in his books in such situation the most important thing is consistency and standardization. If you work in team of few developers you should use common approach to such problem and always use same code pattern to avoid confusion. Because such confusion is a waste of developers time.

I would recommend you this Clean Code: A Handbook of Agile Software Craftsmanship brilliant book about clean code where you can find answers and suggestions for many problems like this one.


In my current team we would use such convention:

PersonDom - person data object model
Person - person view model

Is it good to have the function name same as the event listeners?

Example:

function onClick: function(event){
//body
}

<div class="example" onClick={this.onClick} /> 

it does not matter what coding language do you use, the name of function must be clear for everyone, if you call it "onClick" - and next time someone want to use it - he can not understand what makes this function, and also if you want to call this function from another place - hes name would be illogical.

it would be better to call it something like this :

  1. send_private_message()
  2. get_client_information
  3. do_something()

    -it depends on what this function doings.

If you are interested in "clean code standards" - i think this is the best book about clean coding and naming stadards : clean code

I started my programming life not long ago. It is said that if you combine data and algorithm together, then you got a program. That is exactly what I do now, yet I hear these theories:

  • Build for today, design for tomorrow
  • Before coding, make each module as clear as possible
  • Your code should not be understandable by just a handful of people
  • Prepare for predictable changes

    All in all, I come across no theories about interfaces. I wonder where and when to use interfaces to meets good standards.

    Maybe you know a lot. Then give me some tips! Examples are wonderful!

If you have read all this jargon, but not yet found out what they mean, then you are not reading all the right books.

Try:

  1. Robert C. Martin (unclebob)'s Clean Code.
  2. Michael Feather's "Working effectively with Legacy Code".

I know it helped me a lot.

Cheers

It is not a problem i was just in the search for a product that could automatically comment code. Through analysing methods and what the code is actually doing. The closest thing that i found to this was Ghost Doc. But that is not what the company is looking for. They want a system that could look at could written thus far and well push out some semi understandable information regarding the code. Seems it's more for business than succession planning. Any guidence to a application or something that is capable of doing this would be great. Even though i personally think it is impossible.

Rowland is spot on. I think your organization should start investing in writing better code that needs less comments. Code should explain itself and such code makes most comments redundant. What's left are the unobvious hacks and performance tweaks. Those should be commented.

Here is a great reference that I think you and your co-workers all should read: Clean Code.

I try to code a order system and it is my first cake project.

i have a order, a user and a useraddress.

//Order model
public $belongsTo = array(

    'User' => array(
        'className' => 'User'
));

//User model
public $hasOne = array(
    'Useradr' => array(
        'className' => 'Useradr',
        'foreignKey' => 'user_id',
        'order' => ''
   )
);
//maybe not necessary Useradr model

public $belongsTo = 'User';

Now i want to access the useraddress while i add/edit a voucher.

I can access the User in the voucher edit view:

 echo $this->Form->input('User.email',array(
        'label' => 'Email',
    ));

But not the Useraddress. What iam doing wrong ?

Thank you very much!

Julius

You have to use the correct model prefix.

echo $this->Form->input('Useradr.some_field',array(
        'label' => 'Some Field',
    ));

I suggest you to do the blog tutorial instead of starting blindly coding. Also reading about the conventions is a good idea.

Further Useradr is a pretty bad name, better would be UserAddress. Abbreviations suck for multiple reason. First they're hard to guess if you don't know what they mean and the inflector very likey does not like them either and might screw up the singular/plural cases. Read Clean Code, very nice book about how to write clean code.

I've been trying to find a better way to handle my error states.

Currently I have about 10 if else statements, which clearly is an inefficient way to handle my errors.

From what I've been able to find, it looks like enumerations are the way to go. But I havn't been able to implement it successfully.

Every example I've been able to find follow this form:

enum Result<T> {
    case Success(T)
    case Failure(String)
}

var result = divide(2.5, by:3)

switch result {
case Success(let quotient):
    doSomethingWithResult(quotient)
case Failure(let errString):
    println(errString)
}

But I don't quite see how this can work for my error states.

There's no if statements, not to mention explanation of where to implement these, and they all only have 1 "action" In the above example a println.

I have several lines of code I need to run for every error state.

Here's an example of my errorhandling for an email textfield.

    if textField == emailTextField {
        emailTextField.textColor = UIColor.formulaBlackColor()
        emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
        emailTextField.resignFirstResponder()
        if textField.text.isEmpty {
            emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
            emailState.text = ""
            emailTextField.attributedPlaceholder = NSAttributedString(string:"Email Address",
                attributes:[NSForegroundColorAttributeName: UIColor.formulaRedColor()])
            showError("Please enter your email.")
        } else if emailTextField.text.isValidEmail() == false {
            emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
            emailTextField.textColor = UIColor.formulaRedColor()
            emailState.text = ""
            showError("Please enter a valid email address")
        } else {
            emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
            emailState.textColor = UIColor.formulaGreenColor()
            emailState.text = ""
            hideError()
        }
    }

I've been trying to make an enum like this:

enum Login {
    case NoInternetConnection
    case NoEmail
    case InvalidEmail
    case NoPassword
    case WrongEmailOrPassword
    case Success
}

But I havn't found a way to make this work.

When I added a switch case, I was presented with an error "Expected Declaration",

I tried putting it in a function, and the error went away. But I havn't been able to figure out how to do anything with the cases.

switch Login {
case Success:println("CASE SUCCESS")
case NoEmail:println("CASE NoEmail")
}

Obviously I still have to implement my if statements in some way to check e.g. if the emailTextField is empty? But how can I set the case to NoEmail. And make it run several lines of code?

You need to have a value of that enumeration first, that you can check, like so:

enum Login {
    case NoInternetConnection
    case NoEmail
    case InvalidEmail
    case NoPassword
    case WrongEmailOrPassword
    case Success
}

// Here you get your result, e.g. from a function.
let loginResult = Login.Success

switch loginResult {
case let .NoInternetConnection:
    println("No internet connection")
case let .NoEmail:
    println("No email specified")
case let .InvalidEmail:
    println("Email invalid")
case let .NoPassword:
    println("No password specified")
case let .WrongEmailOrPassword:
    println("Email or password wrong")
case let .Success:
    println("Success")
}

Remember that there is also another way to go, which is Optional Chaining.

In my opinion, it is always best to break such conditional chains up into several functions (see also Clean Code), but unfortunately Swift does not support catching exceptions, so we have to go this way.

I've never asked anything this general before, and I'm not sure if it's going to sound like I'm asking for someone to do my work for me. I'm an experienced programmer but I'm somewhat new to the kinds of design patterns that get talked about on sites like this.

Synopsis of parameters:

(1) There are 3 external systems that are effectively data stores

System1 - REST System2 - WSDL System3 - COM Interop

(2) Data entities are meaningful in 2 of the systems, moving both to and from (the 2 respective systems)

(3) The whole thing is driven by a synchronization manager app.

Synopsis of implementation:

(4) Data entities are defined by interfaces living in a separate namespace.

IFoo IBar IBaz

(5) Work is done by Utility classes that live in a namespace dedicated to the system.

namespace MyCompany.Integrations.System1 {
 public static class Utility {
  public static List<IFoo> GetFoos(DateTime since) {...}
  public static void SaveBazes(List<IBaz> bases) {...}
 }
}

namespace MyCompany.Integrations.System2 {
 public static class Utility {
  public static void SaveFoos(List<IFoo> foos) {...}
  public static List<IBar> GetBars(DateTime since) {...}
 }
}

namespace MyCompany.Integrations.System3 {
 public static class Utility {
  public static void SaveFoos(List<IFoo> foos) {...}
  public static void SaveBars(DateTime since) {...}
 }
}

Question: What existing patterns, if any, is this similar to and are there any areas I might explore to help me learn how to improve my architecture? I know the Utility classes aren't OO. I haven't figured out how to layout classes to get it done in a simple way yet.

Addition: I thought more and based on one response, I think I was not specific enough. I am hoping someone who had more experience tells me how to apply some OO patterns and get away from Utility classes

10,000 foot answer:

You might find Domain Driven Design and Clean Code useful as they give you a set of patterns that work well together and a set of principals for evaluating when to apply a pattern. DDD resources: the book, free quick intro, excellent walkthrough. Clean Code resources: summary, SOLID principles.

Specific answer:

You are already using the Repository pattern (your utility classes) which I'd probably use here as well. The static members can make the code difficult to test but otherwise aren't a problem. If the Repositories become too complex, break out the low-level API communication into Gateways.

Since an entity is split across multiple data sources, consider modelling this explicitly. For example: Person, HumanResourcesPerson, AccountingPerson. Use names understood by the external systems and their business owners (e.g. Employee, Resource). See Single Responsibilty Principle and Ubiquitous Language for some reasoning. These may be full Entities or just Data Transfer Objects (DTOs) depending on how complex they are.

The synchronization might be performed by an Application Service that coordinates the Repositories and Entities.

I've seen a lot of methods in these two style:

1.
void foo() {
  if(!good) {
    return;
  }
  doFoo();
}

2.
void foo() {
  if(good) {
    doFoo();
  }
}

I wonder if this is just a matter of taste or one is actually better than the other. Does anyone know any evidence about this? (Style-checker rules, book, etc.) I'm thinking mainly about this code written in Java.

First variant handle extra nesting. It depends on your project's code style conventions and your method logic. I advice you to read Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin

I would like to see/learn how solid principles are utilized in a right way in a real projects.

Or there is none?

<shameless plug>

You can have a look at the source code of my project. I've tried to follow the SOLID principles and the recommendations of the Clean Code book. For example following SRP has caused the classes to be very small and focused - the largest classes are only about 200 LOC (when counting whitespace, copyright statements and comments). It's all in Java, but that is close enough to C#, and the principles are anyways the same.

</shameless plug>

My question has Bash and PowerShell scripts in mind, but I suppose it applies to other languages as well.

It is my understanding that the purpose of a function is to perform the same (or a very similar) task multiple times. This decreases the amount of code in the script and it also makes it easier to maintain.

With that in mind, if you discover that your script only calls a function one time then there's no reason for that function to exist as a function. Instead, you should take the function's code and place it in the location where that function is being called.

Having said all that, here's my question:

If I have a complicated script, should I move each section of code into its own function even though each function will only be called once? This would greatly increase the script's readability because its logic (the functions) would all be at the top of the script and the flow of execution would be at the bottom of the script. Since 50 lines of code would be represented by just 1 line, it would be much easier to understand what the script is doing.

Do other people do this? Are there disadvantages to this approach?

Read this book

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Here are some quotes from the book.

"Small! The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that."

"FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL.THEY SHOULD DO IT ONLY."

Say I have the following code, which cannot be modified:

class A {
    public doSomething() {
        // lots of business logic
        data = obtainData();
        // lots of other business logic which depends on data
    }

    private obtainData() {
        // connect to the database
        // send web requests
        // send manned missions to the moon
        // process the obtained data
        return data;
    }
}

What are the best practices of testing such a code? I want to make sure doSomething() does what it should do, but I want to provide it with known data instead of running the code inside obtainData().

Have a look at Moles to help you with brownfield testing. Moles in C# allow you provide your own implementations for private code and other people's code.

When you have a good set of tests that cover this mess, please re-factor to save humanity.

If the originator of the spaghetti code is within reach, please smack him for me, why don't ya?

For best practices, read Uncle Bob's Clean Code http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

To summarize: if code under test has external dependencies, make them explicit and externally-configurable.

So at present I am learning VB and I have a project in which I have to display a picture box based on:

Which radio box is checked

and

if a checkbox to make the picture box visible is checked. As someone who values clean, good code this is my code and it horrifies me. My question, is there some way to condense the following using cases or some other construct I don't know in VB.net?

    If CheckBox1.Checked = False Then
        BooksPictureBox.Visible = False
        MusicPictureBox.Visible = False
        PeriodicalsPictureBox.Visible = False
        CoffeeBarPictureBox.Visible = False
    End If
    If RadioButton1.Checked And CheckBox1.Checked = True Then
        BooksPictureBox.Visible = True
        MusicPictureBox.Visible = False
        PeriodicalsPictureBox.Visible = False
        CoffeeBarPictureBox.Visible = False
    End If
    If RadioButton2.Checked And CheckBox1.Checked = True Then
        BooksPictureBox.Visible = False
        MusicPictureBox.Visible = True
        PeriodicalsPictureBox.Visible = False
        CoffeeBarPictureBox.Visible = False
    End If
    If RadioButton3.Checked And CheckBox1.Checked = True Then
        BooksPictureBox.Visible = False
        MusicPictureBox.Visible = False
        PeriodicalsPictureBox.Visible = True
        CoffeeBarPictureBox.Visible = False
    End If
    If RadioButton4.Checked And CheckBox1.Checked = True Then
        BooksPictureBox.Visible = False
        MusicPictureBox.Visible = False
        PeriodicalsPictureBox.Visible = False
        CoffeeBarPictureBox.Visible = True
    End If

Note- all the images stack on one another, and all of them start without being visible.

Maybe this?

' Set first condition, the check box must be checked
BooksPictureBox.Visible = CheckBox1.Checked
MusicPictureBox.Visible = CheckBox1.Checked
PeriodicalsPictureBox.Visible = CheckBox1.Checked
CoffeeBarPictureBox.Visible = CheckBox1.Checked

' Set individual conditions, the radio button must be checked
BooksPictureBox.Visible = RadioButton1.Checked
MusicPictureBox.Visible = RadioButton2.Checked
PeriodicalsPictureBox.Visible = RadioButton3.Checked
CoffeeBarPictureBox.Visible = RadioButton4.Checked

Edit: Or, you could take a different Clean Code approach :)

ShowOrHidePictureBoxes()

...

Private Sub ShowOrHidePictureBoxes
  ShowOrHideBooks()
  ShowOrHideMusic()
  ShowOrHidePeriodicals()
  ShowOrHideCoffeeBar()
End Sub

Private Sub ShowOrHideBooks
  BooksPictureBox.Visible = RadioButton1.Checked And CheckBox1.Checked
End Sub

Private Sub ShowOrHideMusic
  BooksPictureBox.Visible = RadioButton2.Checked And CheckBox1.Checked
End Sub

Private Sub ShowOrHidePeriodicals
  BooksPictureBox.Visible = RadioButton3.Checked And CheckBox1.Checked
End Sub

Private Sub ShowOrHideCoffeeBar
  BooksPictureBox.Visible = RadioButton4.Checked And CheckBox1.Checked
End Sub

You could take this further in two ways:

  1. Extract the logic out into a shared helper class to re-use throughout the application, or even into actual models which represent the business concepts in the application. This will depend heavily on how the rest of the application is to be designed, what the business needs are, etc. In the context of this question it's more of a thought exercise than a real answer.
  2. Name your controls better so that the code looks more expressive. Things like CheckBox1 and RadioButton1 pollute the code more than the If statements did :)

So I am currently reading through Clean Code and I really like the idea of super small functions that each tell their own "story". I also really like the way he puts how code should be written to be read in terms of "TO paragraphs", which I've decided to kind of rename in my head to "in order to"

Anyway I have been refactoring alot of code to include more meaningful names and to make the flow in which it will be read a little better and I have stumbled into something that I am unsure on and maybe some gurus here could give me some solid advice!

I know that code-styles is a highly controversial and subjective topic, but hopefully I wont get reamed out by this post.

Thanks everyone!

PSA: I am a noob, fresh out of College creating a web app using the MEAN stack for an internal project in an internship at the moment.

Clean Code refactor

 //Modal Controller stuff above.  vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();

  function castTaskDataTypesForForm() {
    castPriorityToInt();
    castReminderInHoursToInt();
    castDueDateToDate();
    getAssigneObjFromAssigneeString();
  }

  function castPriorityToInt() {
    vm.task.priority = vm.task.priority === undefined ?
      0 : parseInt(vm.task.priority);
  }

  function castReminderInHoursToInt() {
    vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
      0 : parseInt(vm.task.reminderInHours);
  }

  function castDueDateToDate() {
    vm.task.dueDate = new Date(vm.task.dueDate);
  }

  function getAssigneObjFromAssigneeString() {
    vm.task.assignee = getUserFromId(vm.task.assignee);
  }

Possibly better refactor? / My question ----------------------------

//Modal Controller stuff above.  vm.task is an instance variable
vm.task = vm.data.task;
castTaskDataTypesForForm();

  function castTaskDataTypesForForm() {
    castPriorityToInt();
    castReminderInHoursToInt();
    castDueDateToDate();
    getAssigneObjFromAssigneeString();

    function castPriorityToInt() {
      vm.task.priority = vm.task.priority === undefined ?
        0 : parseInt(vm.task.priority);
    }

    function castReminderInHoursToInt() {
      vm.task.reminderInHours = vm.task.reminderInHours === undefined ?
        0 : parseInt(vm.task.reminderInHours);
    }

    function castDueDateToDate() {
      vm.task.dueDate = new Date(vm.task.dueDate);
    }

    function getAssigneObjFromAssigneeString() {
      vm.task.assignee = getUserFromId(vm.task.assignee);
    }
  }

Posting the IIFE example here so I have more room to work with. I'm not saying this is the best option, it's the one I would use with the info the OP gave us.

var castTaskDataTypesForForm = (function() {
    var castPriorityToInt = function castPriorityToInt() { ... },
        castReminderInHoursToInt = function castReminderInHoursToInt() { .. },
        castDueDateToDate = function castDueDateToDate() { ... },
        getAssigneObjFromAssigneeString = function getAssigneObjFromAssigneeString() { ... };
    return function castTaskDataTypesForForm() {
        castPriorityToInt();
        castReminderInHoursToInt();
        castDueDateToDate();
        getAssigneObjFromAssigneeString();
    };
}());
vm.task = vm.data.task;
castTaskDataTypesForForm();

This way the helper functions only get defined once and are kept private inside the closure. You can obv remove the var x = function x syntax if you prefer the function x() style.

edit: If the function only gets called once, your own examples are probably the cleaner code. The reason you'd use the IIFE syntax would be to keep the helper functions only accesible by the main function, like in your own second example.

So I'm new with iOS but seasoned with Android and I'm starting to get the gist of most stuff but I have a hard time understanding what goes where, why it is like this...

When you use storyboards only it's easy enough to implement MVC pattern (or any other view seperation pattern), but when you make everything in code I feel it gets little messy.

Lets say I have a ViewController with a parent View containing children Views, which again might contain children Views. Now where should I create the children? In the ViewController (most convenient) or in the parent View (nearest)?

If I use the ViewController I have reference and I'll have an easy time making outlets etc. but should the ViewController then also do stuff like setTitle, setImage, background etc. etc.? This will definitely be the easiest solution. The disadvantage is that Views are simply just objects making which will result in the ViewController becoming bloated.

If I use the View I'll have a hard time returning outlets to the ViewController and the ViewController will end up doing nearly nothing.

Apple isn't much help either, the officiel FoodTracker tutorial shows both ViewController and Views using outlets etc. etc.

Basic structure I have right now:

updateLayoutStates()
setupLayoutPositions()
updateLayoutPositions()

...

/// Setups the initial constraints for all views
func setupLayoutPositions() {

    // add views by order of appearances
    addSubview(languageBtn)
    addSubview(playBtn)
    addSubview(menuBtn)
    //addSubview(barScrollOverlayView)
    addSubview(barScrollView)
    addSubview(collapseBtn)

    // add bar scroll inner subviws by order of appearance
    barScrollView.addSubview(barScrollContentView)

    barScrollContentView.addSubview(speedContainerView)
    barScrollContentView.addSubview(speedProgress)
    barScrollContentView.addSubview(readingStratBtn)
    // More code that adds constraints etc. etc.

...

/**
 Updates all views based on the current status of the bar
 */
func updateLayoutStates() {
    print("Bar updateLayoutStates")

    // setup base layout
    // setup permanent items, listed by appearance
    languageBtn.backgroundColor = UIColorFromHex(Constants.Colors.dark_blue, alpha: 1)
    languageBtn.setTitle("lang_da".localized, forState: .Normal)
    languageBtn.postSetup()
    languageBtn.setTitleColor(UIColorFromHex(Constants.Colors.white, alpha: 1), forState: .Normal)

    playBtn.setImage(UIImage(named: "Play"), forState: .Normal)
    playBtn.setImage(UIImage(named: "PlayActive"), forState: .Highlighted)
    playBtn.setTitle("label_play_key".localized, forState: .Normal)
    playBtn.postSetup()

   ...

/// updates the positions of all layouts based on the current status of the bar
func updateLayoutPositions() {
    if currentBarState == BarState.EnabledStandardExpanded {
        self.removeConstraint(collapseLeftConstraint)
        self.addConstraint(collapseRightConstraint)
    } else if currentBarState == BarState.EnabledStandardCollapsed {
        self.removeConstraint(collapseRightConstraint)
        self.addConstraint(collapseLeftConstraint)
    }
}

All explanation with examples is greatly appreciated and I'll be happy to explain further if I haven't been clear enough.

At one hand you are talking about good architecture. On the other hand you want some help with your specific view structure.

1) For the first part you have many resources out there. DJohnsen already mentioned MVVM and VIPER which I think is a good search string for Google. I think it is always good to get comfortable with architecture topics. And every architecture has trade offs. A good starting point is Uncle Bobs "Clean Code".

From there many ideas evolved.

2) Regarding your view problem:

If you have a nested view hierarchy it might be a good idea to think of view controller containment. As soon as you see, that your view is composed out of many other views and it gets more complex you might want to split the components. You always have to think about the concrete problem you are trying to solve:

  • Do you only want to display one label and a button? Add them directly to the view controller and connect the outlets or setup target/action.

  • Do you have a complex view with headers, custom subviews, maybe also a tableView etc? Use child view controllers

But to break it down:

View controllers and views are very close to each other. In iOS I started to handle views and view controllers in the following way:

  • Views controllers should be dumb. Their only purpose is to manage child controllers or to set properties of a few views. View controllers also manage high level screen handling (device rotation, status bar handling etc) and talk with the presentation layer.

  • Views are more dumb and should only setup the subviews, layout (set Layout constraints) and provide some methods for customization (which can be used by the view controller).

It all sounds a bit hard: But I think it is a good guideline for beginners. After some time you will get comfortable.

The questions you ask are good ones but you will answer them by yourself after some time. I think the most important thing is that you should put only view specific code into view controllers and views. Not more.

All the rest quickly escalates to religious wars :)

Cheers
Orlando

Using:

node.js

Problem:

While refactoring my code today I saw these chunks of lines. The interesting thing about them is that each alternative line in the try catch can cause and exception and hence the code can crash. For what practice I follow, each individual exception should be handled specifically and minimum (useful) lines of code should be in the try catch. As a programmer which approach should I be following (A , B , anyother)? And why? I personally would go with A as it decreases the number of lines in code.

Code A:

function(err, someData, res){
    if(err){
        console.error(err);
    } else{

        try{
            data = JSON.parse(someData); //exception expected

            if(someVariable == "abc"){
                var items = data['a']; //exception expected
            } else if(site == "xyz"){
                var items = data['b']; //exception expected
            }

        } catch(err){
            console.error(err);
        }
}

Code B:

function(err, someData, res){
    if(err){
        console.error(err);
    } else{

        try{
            data = JSON.parse(someData); //exception expected
        } catch(err){
            console.error(err);
        }

        if(someVariable == "abc"){
            try{
                var items = data['a']; //exception expected
            } catch(err){
                console.error(err);
            }
        } else if(site == "xyz"){
            try{
                var items = data['b']; //exception expected
            } catch(err){
                console.error(err);
        }
            }
}

A with a Twist

In "Clean Code", "Uncle Bob" Martin holds that try/catching exceptions is a specific task worthy of its own function. Extract the real work into a separate method. This silly suggestion made me rant at first, but I have grown to actually like the idea.

parseData = function(someData, res) {
    data = JSON.parse(someData); //exception expected

    if(someVariable == "abc"){
        var items = data['a']; //exception expected
    } else if(site == "xyz"){
        var items = data['b']; //exception expected
    }
}

tryParseData = function(err, someData, res){
    if(err) {
        console.error(err);
    } else {
        try {
            parseData(someData, res);
        } catch(err) {
            console.error(err);
        }
    }
}

This question is based on Clean Code, chapter "Functions", section "The Error.java dependency magnet".

public enum Error {
      OK,
      INVALID,
      NO_SUCH
}

The author claims that all classes that import and use this enum must be recompiled in case of a change. This is opposed to adding new Exception derivatives. In the latter case there is supposedly no recompilation necessary.

But isn't it the case that if you use the package that has the derived exceptions as soon as the package is changed by adding a new derived Exception, if your code depends on the package it will need to be recompiled? Or will you code only need to be recompiled if it actually uses one of the new derived Exceptions?

Here's a snippet from inside a python class used in a web scraping project. I want to iterate through a dictionary of freshly scraped data, comparing it to the previously scraped index at each level, and adding values that need updating to another deeply nested dict for later processing. What strategies can I use to clean this up and still accomplish the same results?

self.new_stats[tour] = {}
parsed_stats = parse_stat_year(CURRENT_STAT_YEAR, self.scraped_stats_index[tour])

for pname, stats_by_year in parsed_stats.items():
  if pname in self.raw_players_with_stats[tour]:
    player = self.raw_players_with_stats[tour][pname]

    if 'stats' in player:
      for y, stats_by_cat in stats_by_year.items():
        if str(y) in player['stats']:
          for cat, stat in stats_by_cat.items():
            if cat in player['stats'][str(y)]:
              for prop, val in stat.items():
                if (not prop in player['stats'][str(y)][cat]) or (player['stats'][str(y)][cat][prop] != val):
                  self.new_stats[tour].setdefault(pname,{}).setdefault(y,{}).setdefault(cat,{})[prop] = val
            else:
              self.new_stats[tour].setdefault(pname,{}).setdefault(y,{})[cat] = stat
        else:
          self.new_stats[tour].setdefault(pname,{})[y] = stats_by_cat
    else:
      self.new_stats[tour][pname] = stats_by_year

  elif pname in self.new_player_urls[tour]:
    self.new_stats[tour][pname] = stats_by_year

I would start with unit test to ensure that after each refactoring iteration my code still actually works.

I would use meaningful data structures and methods, so the code is more self-describing. Sometimes you can find namedtuple very useful for that if you don't want to roll out a separate data-holder class.

Finally I would decompose this big and ugly if...for...else block into meaningful smaller chunks, something like this:

# instead of this original code...

for pname, stats_by_year in parsed_stats.items():
  if pname in self.raw_players_with_stats[tour]:
    #...
  elif pname in self.new_player_urls[tour]:
    self.new_stats[tour][pname] = stats_by_year

# you get something like this

for player_name, stats_by_year in parser_stats.iteritems():
  if self.has_raw_player(player_name):
    self.process_new_raw_player(player_name, stats_by_year)
  elif self.is_player_new(player_name):
     self.insert_new_stat_for_player( player_name, stats_by_year )

which is easier to read, test and understand

And, if you have some free time, I would invest it in reading Clean Code by Robert Martin. It will pay off surely!

Edit

Clean up lengthy and difficult to read one-liners like this

#...
self.new_stats[tour].setdefault(pname,{}).setdefault(y,{}).setdefault(cat,{})[prop] = val
#...

So it looks, for example, like this:

def insert_new_stat(self, tour, pname, y, cat, prop, val):
  player_stat = self.new_stats[tour].setdefault(pname, {})
  y_param = player_stat.setdefault(y, {}) # what is y??
  category_stats = ...
  prop_stats = ...
  ... = val

Your code certainly will be more lengthy and verbose, although Explicit is better than implicit

How many :attr_accessors are too many for a class, or, what is the "right" number of such methods (if there is such a thing as a "right number")?

So, as a trivial example, take

class Example
  :attr_accessor :a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k
  # instance methods here...
end

Obviously, sometimes a large number of such variables and the corresponding accessors are necessary (perhaps you'd see this in an ActiveRecord::Model); but I'm looking for a decent heuristic to use when determining whether to refactoring based on the raw number of instance variables within a class.

Answers highlighting and/or summarizing articles, presentation, books, etc. on this design issue are much appreciated.

In object-oriented programming, if the methods that serve a class tend to be similar in many aspects, then the class is said to have high cohesion. In a highly cohesive system, code readability and reusability is increased, while complexity is kept manageable.

wiki here: read me

and this book: Clean code

I am trying to implement and follow some coding standards in my PHP code.

I did read a few question already asked here but I think an attempt to centralise information might help others like me. I found a few resources (6 until now):

The latter has a tool to help comply with it, CodeSniffer, although you can configure it to check for any standards.

Although they do seem to set a common ground, they do show conflicting info, for instance, the first two links, Wordpress recommends to have a space after opening parenthesis and before closing one, while PHP-FIG recommends the opposite: if ( $a === 0 ) v if ($a === 0)

Codeigniter style guide basically contradicts everything in the Wordpress guide...

Are there any other resources that might have a higher authority on the matter? What are others using, or does it even matter to follow a "standard" if it is contradicted by another?

Actually this question is going to get closed because the answers will be opinion based and so is mine:

I would not go by Wordpress, the code of that project is... not good. WP is for sure not popular because of it's "superior" code and architecture. If you want a blog, take it, if you want good examples of development, architecture and best practice - stay far away from it.

PEAR is just outdated IMHO. And it is not just pear that has a code sniffer, phpcs is a generic tool:

https://github.com/squizlabs/PHP_CodeSniffer

Good projects come with a ruleset for their conventions. The sniffer itself comes bundled with a few rulesets like PEAR and I think PSR as well.

The PSR standard is a pretty good one to use except the never ending tab vs space discussion. I personally think spaces for indention over tabs is idiotic because that's exactly what tabs are thought for and virtually every editor can configure the displayed tab size to match X spaces.

So I would recommend the PSR standard.

But I use whatever standard the project I'm working on is using. If I work on CakePHP I use their coding standard, if I have to work on Wordpress (please no!), I'll use theirs. For my own projects I go for PSR.

I would recommend you to read this book in addition:

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

It's using Java for the examples but the language doesn't really matter here.

Whatever standard you use, I'm happy you think about writing clean code and that you want to make sure you have a standard! Many "developers" just don't care and write a huge mess.

I have a C# project that needs to refactor. Project uses WPF+MVVM Light toolkit. I found the MainViewModel(...) constructor that receives about 50 parameters (factories interfaces). I think not. Am I right? I'm interested, because I want to improve my OOP thinking. Thanks.

P.S. Sorry for my grammar. Check me if you find errors.

Clean Code: A Handbook of Agile Software Craftsmanship, page 40, states that...

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

Consider the book as guidelines for software design, and as such, recommendations when thinking about your code structure.

I have the following example data array:

$data = [];
$data["general"]["login"] = "Auth"
$data["general"]["login_failed"]["err1"] = "First error"

and the following request var:

$reqvar = "['general']['login']";

I'd like to:

print_r($data{$reqvar});

which would translate as

print_r($data['general']['login']);

but it doesn't seems to work

I'm not willing to iterate over the full array, it doesn't make sense considering that I know the path of the value that I want to print.

Thank you

First of all take a look on PHP documentation - Arrays:

"Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above)."

So I think you are trying something like that:

<?php

$data = [];
$data["general"]["login"] = "Auth";
$data["general"]["login_failed"]["err1"] = "First error";

$reqvar1 = 'general';
$reqvar2 = 'login';

print_r($data{$reqvar1}{$reqvar2});

I strongly suggest you to refactor your code. Take a look on:

Regards,

im a beginner in coding and I got stuck with this question.. My code is very long and its not working. The question is: write a function that will calculate the sum of two polynomials. A polynomial is displayed as (base, exponent). For example:

(3,4)(-2,2)(15,0) is 3x^4-2x^2+15. 

If we have:

list1=(11,10)(3,9)(4,7)(20,4)
list2=(8,10)(6,7)(16,1)
list3=list1+list2=(19,10)(3,9)(10,7)(20,4)(16,1)

Each list is expressed as Node where the value of each code is (base, exponent). return a new list which is the sum of the two lists.

Here is the object Polynomial:

import java.util.*;
public class Polynomial {
private int num1;
private int num2;
public Polynomial(int num1, int num2){
    this.num1=num1;
    this.num2=num2;
}
public int getNum1(){
    return this.num1;
}
public int getNum2(){
    return this.num2;
}
public void setNum1(int num1){
    this.num1=num1;
}
public void setNum2(int num2){
    this.num2=num2;
}
}

and the class Node:

import java.util.*;
public class Node<T> {
private T value;
private Node<T> next;
public Node(T value){
    this.value=value;
    this.next=null;
}
public Node(T value, Node<T> next){
    this.value=value;
    this.next=next;
}
public T getValue(){
    return this.value;
}
public Node<T> getNext(){
    return this.next;
}
public boolean hasNext(){
    return (this.next!=null);
}
public void setValue(T value){
    this.value=value;
}
public void setNext(Node<T> next){
    this.next=next;
}
public String toString(){
    return value+ " --> " + next;
}
}

Now here is the function I wrote (sorry for the length):

import java.util.*;
public class q56 {

public static int max(Node<Polynomial> L1, Node<Polynomial> L2){
    int max=0;
    while (L1!=null){
        if (L1.getValue().getNum2()>max){
            max=L1.getValue().getNum2();
        }
        L1=L1.getNext();
    }
    while (L2!=null){
        if (L2.getValue().getNum2()>max){
            max=L2.getValue().getNum2();
        }
        L2=L2.getNext();
    }
    return max;
}

public static int length(Node<Polynomial> L){
    int count=0;
    while (L!=null){
        count++;
        L=L.getNext();
    }
    return count;
}

public static Node<Polynomial> found(Node<Polynomial> L, int max){
    Node<Polynomial> found=null;
    while (L!=null){
        if (L.getValue().getNum2()==max){
            found=L;
        }
        L=L.getNext();
    }
    return found;
}

public static Node<Polynomial> sum(Node<Polynomial> list1, Node<Polynomial> list2){
    Node<Polynomial> listSum=null; Node<Polynomial> posSum=listSum;
    Node<Polynomial> pos1=list1; Node<Polynomial> pos2=list2;
    boolean alreadychecked=false;
        while (pos1!=null){
            while (pos2!=null){
                int max=max(pos1, pos2);
                alreadychecked=false;
                //if the maximum has been found in both of the lists
                if (found(pos1, max)!=null && found(pos2, max)!=null){
                    Node<Polynomial> found1=found(pos1, max);
                    Node<Polynomial> found2=found(pos2, max);
                    Polynomial end=new Polynomial(found1.getValue().getNum1()+found2.getValue().getNum1(), max);
                    if (posSum==null){
                        posSum=new Node<Polynomial>(end);
                        listSum=posSum;
                    }
                    else {
                        posSum.setNext(new Node<Polynomial>(end));
                    }
                    //moves to the next one (in list 1)
                    pos1=pos1.getNext();
                    //moves to the next one (in list2)
                    pos2=pos2.getNext();
                    alreadychecked=true;
                }
                //if the maximum has been found in list 1 (and not in list 2)
                else if((found(pos1, max)!=null && found(pos2, max)==null) && alreadychecked==false){
                    if (listSum==null){
                        listSum=found(pos1,max);
                        posSum=listSum;
                    }
                    else {
                        posSum.setNext(found(pos1,max));
                    }
                    //moves to the next one (in list 1)
                    pos1=pos1.getNext();
                    alreadychecked=true;
                }
                //if the maximum has been found in list 2(and not in list1)
                else if((found(pos1,max)==null && found(pos2,max)!=null) && alreadychecked==false){
                    if (posSum==null){
                        posSum=found(pos2,max);
                        listSum=posSum;
                    }
                    else {
                        posSum.setNext(found(pos2,max));
                    }
                    //moves to the next one (in list 2)
                    pos2=pos2.getNext();
                }

            }
        }

    return listSum;

}

public static void main(String[] args) {
    Polynomial one1=new Polynomial(11,11);
    Polynomial one2=new Polynomial(3,9);
    Polynomial one3=new Polynomial(4,7);
    Polynomial one4=new Polynomial(20,4);
    Polynomial one5=new Polynomial(1,2);
    Node<Polynomial> first=new Node<Polynomial>(one1);
    Node<Polynomial> pos1=first;
    Node<Polynomial> list1=first;
    pos1.setNext(new Node<Polynomial>(one2));
    pos1=pos1.getNext();
    pos1.setNext(new Node<Polynomial>(one3));
    pos1=pos1.getNext();
    pos1.setNext(new Node<Polynomial>(one4));
    pos1=pos1.getNext();
    pos1.setNext(new Node<Polynomial>(one5));
    while (first!=null){
        System.out.println("("+first.getValue().getNum1()+", "+first.getValue().getNum2()+")");
        first=first.getNext();
    }


    Polynomial second1=new Polynomial(8,10);
    Polynomial second2=new Polynomial(6,7);
    Polynomial second3=new Polynomial(4,2);
    Polynomial second4=new Polynomial(16,2);
    Node<Polynomial> second=new Node<Polynomial>(second1);
    Node<Polynomial> pos2=second;
    Node<Polynomial> list2=second;
    pos2.setNext(new Node<Polynomial>(second2));
    pos2=pos2.getNext();
    pos2.setNext(new Node<Polynomial>(second3));
    pos2=pos2.getNext();
    pos2.setNext(new Node<Polynomial>(second4));
    System.out.println();
    while (second!=null){
        System.out.println("("+second.getValue().getNum1()+", "+second.getValue().getNum2()+")");
        second=second.getNext();
    }
    System.out.println();

    Node<Polynomial> end=sum(list1, list2);
    while (end!=null){
        System.out.println("("+end.getValue().getNum1()+", "+end.getValue().getNum2()+")");
        end=end.getNext();
    }
}
}

Explanation: Each time I scanned both of the lists and found the biggest exponent. Then, I checked if that exponent appears in both of the lists or only one of them. If its in both of the lists then I added the bases and kept the exponent (the maximum). If the maximum is found only in one of the lists, I move that cell to the new list and move to the next cell in the list that the maximum was found. After each if, I move to the next cell in either one of the lists or both of them, and then the whole process starts again with a different maximum. I tried the question with these lists:

list1=(11,11)(3,9)(4,7)(20,4)(1,2)
list2=(8,10)(6,7)(4,2)(16,2)

and all I got back was:

(11,11)(16,2)

Thanks for the help!

I can't read your code, so I started writing unit tests to see what it's doing; refactoring as I went. Here's where I landed. You should be able to take it from here. You have to consolidate the merged list into the minimum number of terms.

I renamed your q56 class PolynomialUtils. I added a toString() method because code repetition is the worst thing a programmer can do. Here's what I have so far.

Your Node class:

package math.badpoly;

/**
 * Node
 * Created by eitanmayer
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */

public class Node<T> {
    private T value;
    private Node<T> next;

    public Node(T value) {
        this.value = value;
        this.next = null;
    }

    public Node(T value, Node<T> next) {
        this.value = value;
        this.next = next;
    }

    public T getValue() {
        return this.value;
    }

    public Node<T> getNext() {
        return this.next;
    }

    public boolean hasNext() {
        return (this.next != null);
    }

    public void setValue(T value) {
        this.value = value;
    }

    public void setNext(Node<T> next) {
        this.next = next;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }

        Node<?> node = (Node<?>) o;

        if (!value.equals(node.value)) { return false; }
        return next != null ? next.equals(node.next) : node.next == null;
    }

    @Override
    public int hashCode() {
        int result = value.hashCode();
        result = 31 * result + (next != null ? next.hashCode() : 0);
        return result;
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(this.value.toString());
        if (this.next != null) {
            builder.append(this.next.toString());
        }
        return builder.toString();
    }
}

Your Polynomial class:

package math.badpoly;

/**
 * Polynomial
 * Created by eitanmayer
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */
public class Polynomial {
    private int num1;
    private int num2;

    public Polynomial(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public int getNum1() {
        return this.num1;
    }

    public int getNum2() {
        return this.num2;
    }

    public void setNum1(int num1) {
        this.num1 = num1;
    }

    public void setNum2(int num2) {
        this.num2 = num2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }

        Polynomial that = (Polynomial) o;

        if (num1 != that.num1) { return false; }
        return num2 == that.num2;

    }

    @Override
    public int hashCode() {
        int result = num1;
        result = 31 * result + num2;
        return result;
    }

    @Override
    public String toString() {
        return "(" + num1 + "," + num2 + ")";
    }
}

Your q56 class renamed to PolynomialUtils with new methods added:

package math.badpoly;

/**
 * Created by eitanmayer
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */
public class PolynomialUtils {

    public static int max(Node<Polynomial> list1, Node<Polynomial> list2) {
        return Math.max(maxExponent(list1), maxExponent(list2));
    }

    public static int maxExponent(Node<Polynomial> polynomial) {
        int max = Integer.MIN_VALUE;
        Node<Polynomial> node = polynomial;
        while (node != null) {
            int exponent = node.getValue().getNum2();
            if (exponent > max) {
                max = exponent;
            }
            node = node.getNext();
        }
        return max;
    }

    public static int length(Node<Polynomial> polynomial) {
        int count = 0;
        Node<Polynomial> node = polynomial;
        while (node != null) {
            ++count;
            node = node.getNext();
        }
        return count;
    }

    public static Node<Polynomial> found(Node<Polynomial> polynomial, int max) {
        Node<Polynomial> found = null;
        Node<Polynomial> node = polynomial;
        while (node != null) {
            if (node.getValue().getNum2() == max) {
                found = node;
            }
            node = node.getNext();
        }
        return found;
    }

    public static Node<Polynomial> last(Node<Polynomial> polynomialNode) {
        Node<Polynomial> last = polynomialNode;
        Node<Polynomial> node = polynomialNode;
        while (node != null) {
            last = node;
            node = node.getNext();
        }
        return last;
    }

    public static Node<Polynomial> merge(Node<Polynomial> list1, Node<Polynomial> list2) {
        Node<Polynomial> merged = list1;
        Node<Polynomial> last = PolynomialUtils.last(merged);
        last.setNext(list2);
        return merged;
    }

    public static Node<Polynomial> consolidate(Node<Polynomial> list) {
        // TODO: I've left this for you.
        return null;
    }

    public static Node<Polynomial> sum(Node<Polynomial> list1, Node<Polynomial> list2) {
        Node<Polynomial> listSum = PolynomialUtils.merge(list1, list2);
        return listSum;
    }

    public static void main(String[] args) {
        Node<Polynomial> list1 =
                new Node<Polynomial>(new Polynomial(11, 11),
                        new Node<Polynomial>(new Polynomial(3, 9),
                                new Node<Polynomial>(new Polynomial(4, 7),
                                        new Node<Polynomial>(new Polynomial(20, 4),
                                                new Node<Polynomial>(new Polynomial(1, 2))))));
        System.out.println(list1);

        Node<Polynomial> list2 =
                new Node<Polynomial>(new Polynomial(8, 10),
                        new Node<Polynomial>(new Polynomial(6, 7),
                                new Node<Polynomial>(new Polynomial(4, 2),
                                        new Node<Polynomial>(new Polynomial(16, 2)))));
        System.out.println(list2);

        Node<Polynomial> sum = sum(list1, list2);
        System.out.println(sum);
    }
}

I wrote Junit tests for the PolynomialUtils class:

package math.badpoly;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by Michael
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */
public class PolynomialUtilsTest {

    private Node<Polynomial> list1 = createTestPolynomial1();
    private Node<Polynomial> list2 = createTestPolynomial2();


    @Test
    public void testMax() {

        int expected = 11;
        int actual = PolynomialUtils.max(this.list1, this.list2);
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testLength_List1() {
        Assert.assertEquals(5, PolynomialUtils.length(this.list1));
    }

    @Test
    public void testLast_List1() {
        Node<Polynomial> expected = new Node<Polynomial>(new Polynomial(1, 2));
        Assert.assertEquals(expected, PolynomialUtils.last(this.list1));
    }

    @Test
    public void testLength_List2() {
        Assert.assertEquals(4, PolynomialUtils.length(this.list2));
    }

    @Test
    public void testLast_List2() {
        Node<Polynomial> expected = new Node<Polynomial>(new Polynomial(16, 2));
        Assert.assertEquals(expected, PolynomialUtils.last(this.list2));
    }

    @Test
    public void testFound_Success() {
        Node<Polynomial> expected = new Node<Polynomial>(new Polynomial(11, 11), null);
        Node<Polynomial> actual = PolynomialUtils.found(this.list1, 11);
        Assert.assertEquals(expected.getValue().getNum1(), actual.getValue().getNum1());
        Assert.assertEquals(expected.getValue().getNum2(), actual.getValue().getNum2());
    }

    @Test
    public void testMerge() {
        Node<Polynomial> expected = createMergedTestPolynomial();
        System.out.println(list1);
        System.out.println(list2);
        System.out.println(expected);
        Assert.assertEquals(expected, PolynomialUtils.merge(this.list1, this.list2));
    }

    @Test
    public void testToString() {
        String expected = "(11,11)(3,9)(4,7)(20,4)(1,2)";
        Assert.assertEquals(expected, this.list1.toString());
    }

    @Test
    public void testSum() {
        Node<Polynomial> expected = createSumPolynomial();
        Node<Polynomial> x = createTestPolynomial1();
        Node<Polynomial> y = createTestPolynomial2();
        System.out.println(x);
        System.out.println(y);
        Assert.assertEquals(expected, PolynomialUtils.sum(x, y));
    }


    private Node<Polynomial> createTestPolynomial2() {
        Node<Polynomial> list2 =
                new Node<Polynomial>(new Polynomial(8, 10),
                        new Node<Polynomial>(new Polynomial(6, 7),
                                new Node<Polynomial>(new Polynomial(4, 2),
                                        new Node<Polynomial>(new Polynomial(16, 2)))));
        return list2;
    }


    private Node<Polynomial> createTestPolynomial1() {
        Node<Polynomial> list1 =
                new Node<Polynomial>(new Polynomial(11, 11),
                        new Node<Polynomial>(new Polynomial(3, 9),
                                new Node<Polynomial>(new Polynomial(4, 7),
                                        new Node<Polynomial>(new Polynomial(20, 4),
                                                new Node<Polynomial>(new Polynomial(1, 2))))));
        return list1;
    }

    private Node<Polynomial> createMergedTestPolynomial() {
        Node<Polynomial> mergedList =
                new Node<Polynomial>(new Polynomial(11, 11),
                        new Node<Polynomial>(new Polynomial(3, 9),
                                new Node<Polynomial>(new Polynomial(4, 7),
                                        new Node<Polynomial>(new Polynomial(20, 4),
                                                new Node<Polynomial>(new Polynomial(1, 2),
                                                        new Node<Polynomial>(new Polynomial(8, 10),
                                                                new Node<Polynomial>(new Polynomial(6, 7),
                                                                        new Node<Polynomial>(new Polynomial(4, 2),
                                                                                new Node<Polynomial>(new Polynomial(16, 2))))))))));
        return mergedList;
    }



    private Node<Polynomial> createSumPolynomial() {
        Node<Polynomial> expectedSum =
                new Node<Polynomial>(new Polynomial(11, 11),
                        new Node<Polynomial>(new Polynomial(8, 10),
                                new Node<Polynomial>(new Polynomial(3, 9),
                                        new Node<Polynomial>(new Polynomial(10, 7),
                                                new Node<Polynomial>(new Polynomial(20, 4),
                                                        new Node<Polynomial>(new Polynomial(21, 2)
                                                        ))))));
        return expectedSum;
    }
}

The tests pass. All the terms are present in the sum. You have to consolidate like exponent terms.

I'm not going to answer your question, but I will give some advice that you may find useful today or tomorrow if you decide to continue as a programmer.

  1. Write less code.
  2. One of the key skills to learn as a developer is debugging.
  3. Read Bob Martin's Clean Code.
  4. Learn the Java language coding and naming standards. You routinely break them. It makes your code hard to read.
  5. Have a look at JUnit - you'll be glad you did if you continue as a programmer.

I don't think this implementation is optimal. You've caused a problem by mingling the behavior and list behavior together. If you decide to change from a linked list you have to rewrite that class. I think you'll have a better time if they are kept separate.

I'd recommend that you start with a Monomial class: it'll encapsulate the coefficient and exponent as private data members. I think it'd be smart to implement the operations you need (e.g. add, subtract, etc.) on this class. Make sure that these work perfectly before you proceed.

Once that's written and 100% tested, create a Polynomial class. That will manage a collection of Monomials. The key idea is that the choice of collection should not be tied up in either Monomial or Polynomial classes. You are asked to use linked list. When you learn about maps and hash tables in the future you might decided that changing from linked list is a very good idea. You shouldn't have to rewrite either Monomial or Polynomial on that day.

If I were doing it I'd start with an interface that both Monomial and Polynomial could implement:

package math.polynomial;

/**
 * Interface for simple math operations
 * Created by Michael
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */
public interface SimpleMath <T> {
    T add(T other);
    T sub(T other);
    T mul(T other);
    T div(T divisor);
    T pow(int power);
    T differentiate();
    T integrate();
}

I'd code my Monomial implementation:

package math.polynomial;

/**
 * Monomial class for polynomial
 * Created by Michael
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects
 */
public class Monomial implements SimpleMath<Monomial> {

    /** Coefficients smaller than this will be considered as zero. */
    public static final double MIN_COEFF = 1.0E-4;

    private double coeff;
    private int expon;

    public Monomial() {
        this(0.0, 0);
    }

    public Monomial(double coeff) {
        this(coeff, 0);
    }

    public Monomial(int expon) {
        this(1.0, expon);
    }

    public Monomial(double coeff, int expon) {
        this.coeff = coeff;
        this.expon = expon;
    }

    public double getCoeff() {
        return coeff;
    }

    public int getExpon() {
        return expon;
    }

    public Monomial add(Monomial other) {
        if (this.getExpon() != other.getExpon()) throw new ExponentMismatchException(this, other);
        return new Monomial(this.getCoeff()+other.getCoeff(), this.getExpon());
    }

    public Monomial sub(Monomial other) {
        if (this.getExpon() != other.getExpon()) throw new ExponentMismatchException(this, other);
        return new Monomial(this.getCoeff()-other.getCoeff(), this.getExpon());
    }

    public Monomial mul(Monomial other) {
        return new Monomial(this.getCoeff()*other.getCoeff(), this.getExpon()+other.getExpon());
    }

    public Monomial div(Monomial other) {
        return new Monomial(this.getCoeff()/other.getCoeff(), this.getExpon()-other.getExpon());
    }

    public Monomial pow(int power) {
        return new Monomial(this.getCoeff(), this.getExpon()*power);
    }

    @Override
    public Monomial differentiate() {
        return (this.getExpon() == 0) ? new Monomial() : new Monomial(this.getCoeff()*this.getExpon(), this.getExpon()-1);
    }

    @Override
    public Monomial integrate() {
        return new Monomial(this.getCoeff()/(this.getExpon()+1), this.getExpon()+1);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }

        Monomial other = (Monomial) o;

        return Double.compare(other.coeff, this.coeff) == 0 && this.expon == other.expon;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        temp = Double.doubleToLongBits(coeff);
        result = (int) (temp ^ (temp >>> 32));
        result = 31 * result + expon;
        return result;
    }

    @Override
    public String toString() {
        return String.format("(%.3f, %d)", this.getCoeff(), this.getExpon());
    }
}

I'd unit test it within an inch of its life before proceeding:

package math.polynomial;

import org.junit.Assert;
import org.junit.Test;

/**
 * Junit tests for Monomial
 * Created by Michael
 * Creation date 1/9/2016.
 * @link https://stackoverflow.com/questions/34695272/nodet-with-objects/34695704#34695704
 */
public class MonomialTest {

    @Test
    public void testContructor_Constant() {
        double testCoeff = 2.0;
        String testString = "(2.000, 0)";
        Monomial monomial = new Monomial(testCoeff);
        Assert.assertEquals(testCoeff, monomial.getCoeff(), Monomial.MIN_COEFF);
        Assert.assertEquals(0, monomial.getExpon());
        Assert.assertEquals(testString, monomial.toString());
    }

    @Test
    public void testConstructor_UnitCoeff() {
        int testExpon = 2;
        String testString = "(1.000, 2)";
        Monomial monomial = new Monomial(testExpon);
        Assert.assertEquals(1.0, monomial.getCoeff(), Monomial.MIN_COEFF);
        Assert.assertEquals(testExpon, monomial.getExpon());
        Assert.assertEquals(testString, monomial.toString());
    }

    @Test
    public void testConstructor() {
        double testCoeff = 3.5;
        int testExpon = 2;
        String testString = "(3.500, 2)";
        Monomial monomial = new Monomial(testCoeff, testExpon);
        Assert.assertEquals(testCoeff, monomial.getCoeff(), Monomial.MIN_COEFF);
        Assert.assertEquals(testExpon, monomial.getExpon());
        Assert.assertEquals(testString, monomial.toString());
    }

    @Test
    public void testAdd() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 4);
        Monomial expected = new Monomial(7.0, 4);
        Assert.assertEquals(expected, x.add(y));
        Assert.assertEquals(expected, y.add(x)); // Addition is commutative
    }

    @Test(expected = ExponentMismatchException.class)
    public void testAdd_ExponentMismatch() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 2);
        x.add(y);
    }

    @Test
    public void testAdd_Identity() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(0.0, x.getExpon());
        Assert.assertEquals(x, x.add(y));  // Zero is the additive identity
        Assert.assertEquals(x, y.add(x));  // Addition is commutative
    }

    @Test
    public void testSub() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 4);
        Monomial expected = new Monomial(1.0, 4);
        Assert.assertEquals(expected, y.sub(x));
        expected = new Monomial(-1.0, 4);
        Assert.assertEquals(expected, x.sub(y)); // Subtraction is not commutative
    }

    @Test(expected = ExponentMismatchException.class)
    public void testSub_ExponentMismatch() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 2);
        x.sub(y);
    }

    @Test
    public void testMul() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 4);
        Monomial expected = new Monomial(12.0, 8);
        Assert.assertEquals(expected, x.mul(y));
        Assert.assertEquals(expected, y.mul(x)); // Multiplication is commutative
    }

    @Test
    public void testMul_Identity() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(1.0, 0);
        Assert.assertEquals(x, x.mul(y));
        Assert.assertEquals(x, y.mul(x)); // Multiplication is commutative
    }

    @Test
    public void testDiv_ResultOne() {
        Monomial x = new Monomial(3.0, 4);
        Monomial expected = new Monomial(1.0, 0);
        Assert.assertEquals(expected, x.div(x));
    }


    @Test
    public void testDiv_ResultConstantTerm() {
        Monomial x = new Monomial(3.0, 4);
        Monomial y = new Monomial(4.0, 4);
        Monomial expected = new Monomial(0.75, 0);
        Assert.assertEquals(expected, x.div(y));
        expected = new Monomial(4.0/3.0, 0);
        Assert.assertEquals(expected, y.div(x));  // Division is not commutative
    }

    @Test
    public void testDiv() {
        Monomial x = new Monomial(2.0, 3);
        Monomial y = new Monomial(4.0, 4);
        Monomial expected = new Monomial(0.5, -1);
        Assert.assertEquals(expected, x.div(y));
        expected = new Monomial(2.0, 1);
        Assert.assertEquals(expected, y.div(x)); // Division is not commutative
    }

    @Test
    public void testDiv_Zero() {
        Monomial x = new Monomial();
        Monomial y = new Monomial(2.0, 3);
        Monomial expected = new Monomial(0.0, -3);
        Assert.assertEquals(expected, x.div(y));
        expected = new Monomial(Double.POSITIVE_INFINITY, 3);  // Note: No exception is thrown when dividing by 0.0
        Assert.assertEquals(expected, y.div(x));
    }

    @Test
    public void testPow() {
        Monomial x = new Monomial(2.0, 3);
        Monomial expected = new Monomial(2.0, 6);
        Assert.assertEquals(expected, x.pow(2));
    }

    @Test
    public void testPow_ZeroPower_Constant() {
        Monomial x = new Monomial(2.0, 3);
        Monomial expected = new Monomial(2.0, 0);
        Assert.assertEquals(expected, x.pow(0));
    }

    @Test
    public void testDifferentiate() {
        Monomial x = new Monomial(2.0, 3);
        Monomial expected = new Monomial(6.0, 2);
        Assert.assertEquals(expected, x.differentiate());
    }

    @Test
    public void testDifferentiate_Constant() {
        Monomial x = new Monomial(4.0);
        Assert.assertEquals(new Monomial(), x.differentiate());
    }

    @Test
    public void testIntegrate() {
        Monomial x = new Monomial(2.0, 3);
        Monomial expected = new Monomial(0.5, 4);
        Assert.assertEquals(expected, x.integrate());
    }

    @Test
    public void testFundamentalTheoremOfCalculus() {
        Monomial x = new Monomial(2.0, 3);
        Assert.assertEquals(x, x.integrate().differentiate());
        Assert.assertEquals(x, x.differentiate().integrate());
    }

    @Test
    public void testEquals_Null() {
        Monomial x = new Monomial(2.0, 3);
        Assert.assertFalse(x.equals(null));
    }

    @Test
    public void testEquals_Reflexive() {
        Monomial x = new Monomial(2.0, 3);
        Assert.assertTrue(x.equals(x));
    }

    @Test
    public void testEquals_Symmetric() {
        Monomial x = new Monomial(2.0, 3);
        Monomial y = new Monomial(2.0, 3);
        Assert.assertTrue(x.equals(y) && y.equals(x));
        Assert.assertTrue(x.hashCode() == y.hashCode());
    }

    @Test
    public void testEquals_Transitive() {
        Monomial x = new Monomial(2.0, 3);
        Monomial y = new Monomial(2.0, 3);
        Monomial z = new Monomial(2.0, 3);
        Assert.assertTrue(x.equals(y) && y.equals(z) && z.equals(x));
        Assert.assertTrue(x.hashCode() == y.hashCode());
        Assert.assertTrue(y.hashCode() == z.hashCode());
        Assert.assertTrue(z.hashCode() == x.hashCode());
    }

    @Test
    public void testEquals_DifferentCoefficients_NotEqual() {
        Monomial x = new Monomial(2.0, 3);
        Monomial y = new Monomial(1.0, 3);
        Assert.assertFalse(x.equals(y));
        Assert.assertFalse(y.equals(x));
        Assert.assertFalse(x.hashCode() == y.hashCode());
    }

    @Test
    public void testEquals_DifferentExponents_NotEqual() {
        Monomial x = new Monomial(2.0, 3);
        Monomial y = new Monomial(2.0, 4);
        Assert.assertFalse(x.equals(y));
        Assert.assertFalse(y.equals(x));
        Assert.assertFalse(x.hashCode() == y.hashCode());
    }
}

IntelliJ tells me that all my tests pass. I have 100% test coverage of methods and 75% coverage of lines.

Now that I had Monomial working perfectly I'd implement Polynomial. It would use the same interface SimpleMath<Polynomial>. It would choose some collection of Monomial that would make the implementation easiest. This is where you'll find that your choice of data structure will make your life harder or easier. The good news is that you can change it without bothering clients of your class, because that implementation detail will be hidden inside your class.

Update:

I finished my implementation for Polynomial. It's surprisingly subtle. I'm very glad that I had good Junit tests. Both Monomial and Polynomial evolved based on test results.

i'm using cakephp version 2.3.6, ive been trying to upload cake to a hostgator server through CPanel but been having problems configuring the index.php file in the webroot but not sure the correct configuration for my version of cake on Cpanel my cpanel username is fredenda I tried to configure this in cpanel but keeps on giving this error message

" Parse error: syntax error, unexpected ';' in /home/fredenda/public_html/index.php on line 41"

however this error isnt in the file, Please can someone help me out. Please check the file below... bless.

<?php
/**
 * Index
 *
 * The Front Controller for handling every request
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc.      
(http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.webroot
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * Use the DS to separate the directories in other defines
 */
 if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}

/**
* These defines should only be edited if you have cake installed in
* a directory layout other than the way it is distributed.
 * When using custom settings be sure to use the DS and do not add a trailing DS.
*/

/**
* The full path to the directory which holds "app", WITHOUT a trailing DS.
 *
 */
if (!defined('ROOT')) {
define('ROOT', DS.'home'.DS.(fredenda);
}

/**
 * The actual directory name for the "app".
 *
 */
if (!defined('APP_DIR')) {
define('APP_DIR', 'app');
}

/**
 * The absolute path to the "cake" directory, WITHOUT a trailing DS.
 *
 * Un-comment this line to specify a fixed path to CakePHP.
* This should point at the directory containing `Cake`.
 *
 * For ease of development CakePHP uses PHP's include_path. If you
 * cannot modify your include_path set this value.
  *
* Leaving this constant undefined will result in it being defined in Cake/bootstrap.php
 *
* The following line differs from its sibling
 * /lib/Cake/Console/Templates/skel/webroot/index.php
 */

 define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'lib')

/**
 * Editing below this line should NOT be necessary.
  * Change at your own risk.
  *
  */
 if (!defined('WEBROOT_DIR')) {
define('WEBROOT_DIR', basename(dirname(__FILE__)));
 }
 if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
 }

// for built-in server
if (php_sapi_name() == 'cli-server') {
if ($_SERVER['REQUEST_URI'] !== '/' && file_exists(WWW_ROOT . $_SERVER['REQUEST_URI'])) {
    return false;
   }
   $_SERVER['PHP_SELF'] = '/' . basename(__FILE__);
   }

    if (!defined('CAKE_CORE_INCLUDE_PATH')) {
if (function_exists('ini_set')) {
    ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR .         ini_get('include_path'));
}
if (!include ('Cake' . DS . 'bootstrap.php')) {
    $failed = true;
}
 } else {
if (!include (CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) {
    $failed = true;
}
 }

if (!empty($failed)) { trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR); }

  App::uses('Dispatcher', 'Routing');

 $Dispatcher = new Dispatcher();
 $Dispatcher->dispatch(
new CakeRequest(),
new CakeResponse()
 );

Open your eyes. ;) The parser is not lying to you. There is a missing ) but I don't think fredenda is a constant so...

define('ROOT', DS.'home'.DS.(fredenda);

This line should be:

define('ROOT', DS . 'home' . DS. 'fredenda');

I would recommend you to get an editor or IDE with proper php syntax highlighting and syntax check to see these kind of syntax issues immediately.

And follow coding standards, there should be a space between the DS and strings like in all the other places. Also a good read this book "Clean Code".

I truly hope this question doesn't get deleted since I really do need help from the programming pros out there...

I've been programming for quite a while (my main platform being .Net), and am about 85% self-taught - Usually from the school of hard-knocks. For example, I had to learn the hard way why it was better to put your configuration parameters in an .ini file (that was easier for my users to change) rather than hard-code them into my main app and now to use the app.config rather than even a config file sometimes. Or what a unit-test was and why it proved to be so important. Or why smaller routines / bits of code are better 90% of the time than one, long worker process...

Basically, because I was thrown into the programming arena without even being shown .Net, I taught myself the things I needed to know, but believe I missed MANY of the fundamentals that any beginner would probably be taught in an intro class.

I still have A LOT more to learn and was hoping to be pointed in the right direction towards a book / web-resource / course / set of videos to really teach the best programming practices / how to set things up in the best way possible (in my case, specifically, for .Net). I know this may seem subjective and every programmer will do things differently, but if there are any good books / resources out there that have helped you learn the important fundamentals / tricks (for example, self-documenting code / design patterns / ) that most good programmers should know, please share!!!

My main platform is .Net.

Thanks!!!!

I was wondering why I can't use throw in the nested catch below, I get an error. What is the way to handle exceptions well in this case?

try {
    /* some code which can throw DataAccessException */
    try {
        /* some code which can throw FileNotFoundException */
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }       
} catch (DataAccessException e) {
    e.printStackTrace();
    throw e;
}

Another example, I'm not sure if I handle exceptions well. I'm not sure about printing the stack trace, is it a good practice?

public class SomeCode {

    public static void main(String[] args) {
        A a = new A();
        a.method1();
    }
}

class A {

    B b = new B();

    public void method1() {

        log.info("I'm gonna call method 2");
        try{
            b.method2();
            log.info("success");
        }
        catch(Exception e) {
            log.info("failure");        
        }
    }
}

class B {

    C c = new C();

    public void method2() {
        log.info("I'm method 2 and I'm gonna call method 3");
        try{
            c.method3();
            log.info("success");
        }
        catch(Exception e) {
            throw e;        
        }
    }
}

class C {

    public void method3() {
        log.info("I'm method 3!");
        try{
            log.info("woo-hoo!");
            /*
                some code which can throw DataAccessException.
            */
        }
        catch(DataAccessException e) {
            e.printStackTrace();
            throw e;
        }
    }
}

Any advices on how to handle exceptions better will be very appreciated.

Just my two cents. On your second example you don't need to use try/catch block on class B as you are just rethrowing the exception. I would re-write that as the following:

class B {

    C c = new C();

    public void method2() throws Exception {
        log.info("I'm method 2 and I'm gonna call method 3");
        c.method3();
        log.info("success");            
    }
}

Printing the stack trace can help the developer understand what is happening but on your example you are ignoring the exception after printing it.

Personally I try to avoid propagating the Exception. If the system can't handle it and recover I prefer to throw an unckecked Exception after catching a checked one and cleaning any resources.

If you have the opportunity take a look at chapter 7 on Clean Code book. It covers error handling and is very useful.

There's four arrays and four foreach loops. Two foreach within other two foreach loops, and i want to echo an array value from nested foreach loop. But i don't know why this prints nothing in my browser.

  $abc = array('arif'=>50, 'mofiz'=> 60, 'tofiz'=> 90);
  $def = array('arif'=>55, 'mofiz'=> 65, 'tofiz'=> 95);
  $ghi = array('arif'=>58, 'mofiz'=> 68, 'tofiz'=> 98);
  $jkl = array('arif'=>59, 'mofiz'=> 69, 'tofiz'=> 99);

  foreach ($abc as $ab):

      foreach ($def as $de):


          foreach ($ghi as $gh):
              /*** this echo prints nothing ***/
              echo $gh['arif'];
          endforeach;

          foreach ($jkl as $jk):
          endforeach;

      endforeach;

  endforeach;
$ghi = array('arif'=>58, 'mofiz'=> 68, 'tofiz'=> 98);

foreach ($ghi as $gh):
    echo $gh['arif'];
endforeach;

Let's see how this is evaluated:

  1. Put every element of $ghi into gh variable iteratively.
  2. On first iteration $gh equals to 58
  3. On second iteration $gh equals to 68
  4. On third iteration $gh equals to 98
  5. No more elements in $ghi, done.

That's the reason it's not printing anything - because $gh is not an array and doesn't have arif key.

I suggest you read more about how foreach loop works

And I also suggest you to read a few books on code structure, especially Clean Code

We´re developing a JSON API to deliver data to a handful of clients (namely iOS and Android Apps).

Now, the constantly arising question is: from what point of view do we structure our JSON?

1) 'Client-centric':

The JSONs keys are named after the matching UI elements in the app. e.g.:

{
    "label" : "This is a headline of a news article",
    "textField" : "This is the text of a news article",
}

Pro:

Content of the apps can be changed without releasing new versions of the app. If you wanted to change the content of the UI label, it would look like this:

{
    "label" : "This is a short abstract of a news article"
}

Also, it should be possible to have only one data model related to one view on the client side.

Contra:

Generates clutter on the server-side, as there must be the translation from data object name to UI element name


2) 'Data-centric'

The JSON keys are named after the data entity that delivers the data

{
    "articleHeadline" : "This is a headline of a news article",
    "articleText" : "This is the text of a news article"
}

Pro:

The JSON API says what it does. The key name reveals the content of the key.

Contra:

Generates clutter on the client-side, as there must be the translation from data object name to UI element name

A change in content will also change the name of the JSONs keys.

{
    "articleAbstract" : "This is a short abstract of a news article"
} 

This also requires a code change and deployment of all apps that use the API.


Which one of the two approaches do you prefer and why?

  1. Your API should not know how your app is implemented. It should provide a service but not know what is done with it.

  2. You should provide descriptive names for fields.

  3. The fields in the app should should be changed to descriptive names such as "articleHeadline" and "articleBody".

Update There are two levels you can look at

The Big picture - API design, dependency control, architecture

This article by Robert C. Martin (a.k.a Uncle Bob) is a great starting point. It outlines many of the issues difficulties caused by poor software design and outlines what are known as the SOLID principles of good (solid) software design. I would highly recommend reading, re-reading, and trying to fully understand it.

The Details - Method names, variable names, formatting, comments

This Book also by Robert C. Martin talks about many of the details of writing good code. It also describes what are known as "code smells" or heuristics that indicate there is likely a better solution.

We're supposed to use methods in our program, but I'm having trouble incorporating them into it. My program is like a math game, asking simple addition and addition/subtraction questions. I want all the calculations to be in methods but I'm having trouble returning a whole equation.

I need some assistance when it comes to the direction I need to go in order to use methods effectively in my program, and where I should do my calculations! As well as what should be in its own methods and what should be in the main method.

import javax.swing.*;
import java.io.*;


public class SummativeTwo {

  public static void main (String[] args) throws IOException {

    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in)); {

      Object[] options = {"Yes! I'm Excited!","Im kind of nervous..","Now Way! Ewww!"};
      int n = JOptionPane.showOptionDialog(null, "Welcome Million Dollar Madness! "+ "Are you ready to play?","Welcome",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[2]);
      if (n == JOptionPane.YES_OPTION) {
        JOptionPane.showMessageDialog(null,"Okie Dokie! Lets get started!", "Okie Dokie", JOptionPane.INFORMATION_MESSAGE);
      }
      if (n == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null,"Aw thats okay! Im sure you'll have fun!", "It's okay", JOptionPane.INFORMATION_MESSAGE);
      }
      if (n == JOptionPane.CANCEL_OPTION) {
        JOptionPane.showMessageDialog(null,"Well too bad so sad! You're going to have to play anyways!", "Too bad so sad", JOptionPane.INFORMATION_MESSAGE);
      }

      Object[] optionsA = {"Yes Please", "Nope! I'm good!"};
      int x = JOptionPane.showOptionDialog(null,"Would you like to know the instructions for this game?","INSTRUCTIONS?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]); 
      if (x == JOptionPane.YES_OPTION) {
        JOptionPane.showMessageDialog(null,"There will be 3 levels in this game. As you go farther, the questions get harder and harder and each question \n. Each time you get a question right you will recieve a certain amount of money, which increases each time you pass each question. \n But be careful, because if you get 3 questions wrong in one level \n it's GAME OVER for you! Meaning you lose all your money. \n You may Cash Out at any point if you're not willing to risk losing the amount of money you have. Reach the end of \n the 3 levels and you take home all your money! \n GOOD LUCK!", "Instructions", JOptionPane.INFORMATION_MESSAGE);
      }
      if (x == JOptionPane.NO_OPTION) {
        JOptionPane.showMessageDialog(null,"Suit Yourself! Lets Start!", "Your Choice", JOptionPane.INFORMATION_MESSAGE);
      }
      JOptionPane.showMessageDialog(null,"Welcome to Level: 1 " ," level 1", JOptionPane.INFORMATION_MESSAGE);

      //LEVEL ONE
      int wrong = 0;
      int run = 1;
      int questionnum = 0;
      int amount = 0;

      while (run <= 6 && wrong != 3)
      {
        run ++;
        questionnum++;
        int increment = 150;
        amount += 150;

        int numOne = additionOne ();
        int numTwo = additionTwo ();
        int answer = numOne + numTwo;


        String useranswerA = JOptionPane.showInputDialog(null,"Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer)
        {
          wrong ++;
          JOptionPane.showMessageDialog(null,"You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrong, "Wrong Answer", JOptionPane.INFORMATION_MESSAGE);
          int y = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (y == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (y == JOptionPane.NO_OPTION) {}
        }
        else if (useranswer == answer)
        {
          JOptionPane.showMessageDialog(null,"Correct!", "Right Answer", JOptionPane.INFORMATION_MESSAGE);
          int y = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (y == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (y == JOptionPane.NO_OPTION) {}
        }
      }
      JOptionPane.showMessageDialog(null,"LEVEL ONE COMPLETE!", "LEVEL 1", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null,"Cash on Hand: $ " + amount, "Cash", JOptionPane.INFORMATION_MESSAGE);


      //LEVEL TWO
      JOptionPane.showMessageDialog(null,"Welcome to Level: 2 " ," level 2", JOptionPane.INFORMATION_MESSAGE);
      int wrongB = 0;
      int runB = 1;
      int questionnumB = 0;


      while (runB <= 8 && wrongB != 3)
      {
        runB ++;
        questionnumB++;
        amount += 250;

        int increment = 250;

        int numOne = additionOne ();
        int numTwo = additionTwo ();
        int numThree = numThree ();
        int answer = numOne + numTwo - numThree;


        String useranswerA = JOptionPane.showInputDialog(null,"Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " - " + numThree + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer)
        {
          wrong ++;
          JOptionPane.showMessageDialog(null,"You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrongB, "Wrong Answer", JOptionPane.INFORMATION_MESSAGE);
          int z = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (z == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (z == JOptionPane.NO_OPTION) {}
        }
        else if (useranswer == answer)
        {
          JOptionPane.showMessageDialog(null,"Correct!", "Right Answer", JOptionPane.INFORMATION_MESSAGE);
          int z = JOptionPane.showOptionDialog(null,"CASH OUT with a total of $" + amount + "?","Cash Out?", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,optionsA,optionsA[0]);
          if (z == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null,"Thanks for Playing!", "Thank You!", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
          }
          if (z == JOptionPane.NO_OPTION) {}
        }
      }
      JOptionPane.showMessageDialog(null,"LEVEL TWO COMPLETE!", "LEVEL 2", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null,"Cash on Hand: $ " + amount, "Cash",JOptionPane.QUESTION_MESSAGE);

    }
  }

  public static int additionOne ()
  {
    int x = (int)( Math.random () * 30);
    return x;
  }
  public static int additionTwo ()
  {
    int x = (int)( Math.random () * 30);
    return x;
  }
  public static int numThree ()
  {
    int x = (int) (Math.random () * 15);
    return x;
  }
}

The 1. level and 2. level were almost identical. So extracting first level to separate method will break the code for the next level. The broken syntax guides what information is required from level one to level 2. It seemed that only amount required necessary.

Following this way of refactoring also suggested that the original wrongB and questionnumB were not used properly. I took the liberty to assume that both round have separate wrong- and questionnum-variables.

Problem in this approach is that if code is not well understood and fragile without tests it is likely it will broke. However I have found it to be effective in cases where smaller refactoring steps are not obvious.

In general all methods should be clear to read. Because main method is the most top method it should clearly state what goes on in program. Methods should be on the same level of abstraction and very short.

The information is passed using State-object but in this case simple amount could be returned from runLevel and passed as a parameter to the next.

I don't know if the dialog thing was meant to be cleaned up but I took some steps to reduce repeated code. Whole thing could be polished a lot more more. I hope this might give some guidance...

Clean code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) is very good book about refactoring and making methods and code in genera readable.

Here is my two cents:

public class SummativeTwo {

public static void main(String[] args) throws IOException {
    BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
    {
        showYesNoCancelDialogWithFollowUp(
                "Welcome",
                "Welcome Million Dollar Madness! " + "Are you ready to play?",
                new DialogOption("Yes! I'm Excited!", new InformationDialog("Okie Dokie! Lets get started!", "Okie Dokie")),
                new DialogOption("Im kind of nervous..", new InformationDialog("Aw thats okay! Im sure you'll have fun!", "It's okay")),
                new DialogOption("Now Way! Ewww!", new InformationDialog("Well too bad so sad! You're going to have to play anyways!", "Too bad so sad")));

        showYesNoDialogWithFollowUp("INSTRUCTIONS?",
                "Would you like to know the instructions for this game?",
                new InformationDialog("There will be 3 levels in this game. As you go farther, the questions get harder and harder and each question \n. Each time you get a question right you will recieve a certain amount of money, which increases each time you pass each question. \n But be careful, because if you get 3 questions wrong in one level \n it's GAME OVER for you! Meaning you lose all your money. \n You may Cash Out at any point if you're not willing to risk losing the amount of money you have. Reach the end of \n the 3 levels and you take home all your money! \n GOOD LUCK!", "Instructions"),
                new InformationDialog("Your Choice", "Suit Yourself! Lets Start!"));


        showInformationMessage("Welcome to Level: 1 ", " level 1");

        State state = new State();
        runLevel1(state);
        showInformationMessage("LEVEL ONE COMPLETE!", "LEVEL 1");
        showInformationMessage("Cash on Hand: $ " + state.amount, "Cash");
        showInformationMessage("Welcome to Level: 2 ", " level 2");
        runLevel2(state);
        showInformationMessage("LEVEL TWO COMPLETE!", "LEVEL 2");
        JOptionPane.showMessageDialog(null, "Cash on Hand: $ " + state.amount, "Cash", JOptionPane.QUESTION_MESSAGE);

    }
}

static class State {

    int amount;
}

private static void runLevel1(State state) {
    int maxRuns = 6;
    int maxWrongs = 3;
    int increment = 150;
    runLevel(increment, maxRuns, maxWrongs, state);
}

private static void runLevel2(State state) {
    int maxRuns = 8;
    int maxWrongs = 3;
    int increment = 150;
    runLevel(increment, maxRuns, maxWrongs, state);
}

private static void runLevel(int increment, int maxRuns, int maxWrongs, State state) throws NumberFormatException, HeadlessException {
    int run = 1;
    int questionnum = 0;
    int wrong = 0;
    while (run <= maxRuns && wrong != maxWrongs) {
        run++;
        questionnum++;
        state.amount += increment;

        int numOne = additionOne();
        int numTwo = additionTwo();
        int answer = numOne + numTwo;

        String useranswerA = JOptionPane.showInputDialog(null, "Question #" + questionnum + " is for: $" + increment + "\n" + numOne + " + " + numTwo + " = ?", "Question", JOptionPane.INFORMATION_MESSAGE);
        int useranswer = Integer.parseInt(useranswerA);

        if (useranswer != answer) {
            wrong++;
            showInformationMessage("You got the wrong answer! \n The correct answer is: " + answer + " \n Questions Wrong: " + wrong, "Wrong Answer");
            askForCashOut(state.amount);
        } else if (useranswer == answer) {
            showInformationMessage("Correct!", "Right Answer");
            askForCashOut(state.amount);
        }
    }
}

public static int additionOne() {
    int x = (int) (Math.random() * 30);
    return x;
}

public static int additionTwo() {
    int x = (int) (Math.random() * 30);
    return x;
}

public static int numThree() {
    int x = (int) (Math.random() * 15);
    return x;
}

private static void askForCashOut(int amount) throws HeadlessException {
    if (askYesNo("Cash Out?", "CASH OUT with a total of $" + amount + "?")) {
        showInformationMessage("Thanks for Playing!", "Thank You!");
        System.exit(0);
    }
}

private static void showYesNoCancelDialogWithFollowUp(String title, String text, DialogOption yes, DialogOption no, DialogOption cancel) {
    DialogOption[] options = new DialogOption[]{yes, no, cancel};
    int n = JOptionPane.showOptionDialog(null, text, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
    options[n].dialog.show();
}

private static void showYesNoDialogWithFollowUp(String title, String text, InformationDialog afterYes, InformationDialog afterNo) {
    if (askYesNo(text, title)) {
        afterYes.show();
    } else {
        afterNo.show();
    }
}
private static final String[] YES_NO_OPTIONS = new String[]{"Yes Please", "Nope! I'm good!"};

private static boolean askYesNo(String text, String title) throws HeadlessException {
    int n = JOptionPane.showOptionDialog(null, text, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, YES_NO_OPTIONS, YES_NO_OPTIONS[0]);
    return n == JOptionPane.YES_OPTION;
}

private static void showInformationMessage(String text, String title) throws HeadlessException {
    JOptionPane.showMessageDialog(null, text, title, JOptionPane.INFORMATION_MESSAGE);
}

static class InformationDialog {

    private String text;
    private String title;

    public InformationDialog(String text, String title) {
        this.text = text;
        this.title = title;
    }

    public void show() {
        showInformationMessage(text, title);
    }
}

static class DialogOption {

    String text;
    InformationDialog dialog;

    public DialogOption(String text, InformationDialog dialog) {
        this.text = text;
        this.dialog = dialog;
    }

    @Override
    public String toString() {
        return text;
    }
}

}

Writing a java program is not a big deal .but how to make that program more efficient means less memory consuming, re usability,can any one explain ..how to do that in java ...

Read the below two books

  1. Effective Java
  2. Clean code

Why do we need to organize code? What are the objectives of organizing code. Organizing code is a time consuming process until it becomes habit. I am trying estimate the cost and benefits of organizing any programming code

Organized code becomes much easier to maintain and extend over time than code that is placed wildly about. That's why programmers take so much care to name variables/methods/etc. well, keep methods short and specific, and so on. I would recommend reading Clean Code by Robert Martin.

I got the following error:

error: no matching function for call to 'max(int&, int&, int&, int&)'

My code is:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <time.h>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    srand(time(NULL));
    int g1l= rand()%5;
    int g1r= rand()%5;
    int g2l= rand()%5;
    int g2r= rand()%5;
    int g3l= rand()%5;
    int g3r= rand()%5;
    int g4l= rand()%5;
    int g4r= rand()%5;
    int g5l= rand()%5;
    int g5r= rand()%5;
    int g6l= rand()%5;
    int g6r= rand()%5;
    int manudw = 0;
    int manudd = 0;
    int manudl = 0;
    int lagalw = 0;
    int lagald = 0;
    int lagall = 0;
    int rmadw = 0;
    int rmadd = 0;
    int rmadl = 0;
    int acmilw = 0;
    int acmild = 0;
    int acmill = 0;

    int manudp = ((manudw*3)+(manudd*1));
    int lagalp = ((lagalw*3)+(lagald*1));
    int rmadp = ((rmadw*3)+(rmadd*1));
    int acmilp = ((acmilw*3)+(acmild*1));
    string manud = "Manchester United";
    string lagal = "Los Angeles Galaxy";
    string rmad = "Real Madrid";
    string acmil = "AC Milan";
    string place1 = "Manchester United  |";
    string place2 = "Real Madrid        |";
    string place3 = "AC Milan           |";
    string place4 = "Los Angeles Galaxy |";
    int counter=0;
    int round1;
    int round2;
    int round3;
    int manudgd = 0;
    int rmadgd = 0;
    int acmilgd = 0;
    int lagalgd = 0;
    do
    {
        int manudp = ((manudw*3)+(manudd*1));
        int lagalp = ((lagalw*3)+(lagald*1));
        int rmadp = ((rmadw*3)+(rmadd*1));
        int acmilp = ((acmilw*3)+(acmild*1));
        int manudgd = ((g1l+g3r+g6r)-(g1r+g3l+g6l));
        int rmadgd = ((g2l+g3l+g5r)-(g2r+g3r+g5l));
        int acmilgd = ((g2r+g4l+g6l)-(g2l+g4r+g6r));
        int lagalgd = ((g1r+g4r+g5l)-(g1l+g4l+g5r));
        cout<<place1<<" "<<manudw<<" | "<<manudd<<" | "<<manudl<<" | "<<manudp<<" | "<<manudgd<<"  |"<<endl<<
              place2<<" "<<rmadw<<" | "<<rmadd<<" | "<<rmadl<<" | "<<rmadp<<" | "<<rmadgd<<"  |"<<endl<<
              place3<<" "<<acmilw<<" | "<<acmild<<" | "<<acmill<<" | "<<acmilp<<" | "<<acmilgd<<"  |"<<endl<<
              place4<<" "<<lagalw<<" | "<<lagald<<" | "<<lagall<<" | "<<lagalp<<" | "<<lagalgd<<"  |"<<endl<<endl;
//        if(max(manudgd,rmadgd,lagalgd,acmilgd)==manudgd || max(manudgd,rmadgd,lagalgd,acmilgd)==rmadgd || max(manudgd,rmadgd,lagalgd,acmilgd)==lagalgd || max(manudgd,rmadgd,lagalgd,acmilgd)==acmilgd)
        if(counter==0)
        {
            for(round1=0;round1<=0;round1++)
            {
                cout<<"Manchester United "<<g1l<<"-"<<g1r<<" Los Angeles Galaxy"<<endl;
                cout<<"Real Madrid "<<g2l<<"-"<<g2r<<" AC Milan"<<endl<<endl;
                int manudgd = ((g1l)-(g1r));
                int rmadgd = ((g2l)-(g2r));
                int acmilgd = ((g2r)-(g2l));
                int lagalgd = ((g1r)-(g1l));
                if(g1l>g1r)
                {
                    manudw++;
                    lagall++;
                }
                else if(g1l<g1r)
                {
                    lagalw++;
                    manudl++;
                }
                else if(g1l==g1r)
                {
                    manudd++;
                    lagald++;
                }
                if(g2l>g2r)
                {
                    rmadw++;
                    acmill++;
                }
                else if(g2l<g2r)
                {
                    rmadl++;
                    acmilw++;
                }
                else if(g2l==g2r)
                {
                    rmadd++;
                    acmild++;
                }
            }
        }
        else if(counter==1)
        {
            for(round2=0;round2<=0;round2++)
            {
                cout<<"Real Madrid "<<g3l<<"-"<<g3r<<" Manchester United"<<endl;
                cout<<"AC Milan "<<g4l<<"-"<<g4r<<" Los Angeles Galaxy"<<endl<<endl;
                int manudgd = ((g1l+g3r)-(g1r+g3l));
                int rmadgd = ((g2l+g3l)-(g2r+g3r));
                int acmilgd = ((g2r+g4l)-(g2l+g4r));
                int lagalgd = ((g1r+g4r)-(g1l+g4l));
                if(g3l>g3r)
                {
                    rmadw++;
                    manudl++;
                }
                else if(g3l<g3r)
                {
                    manudw++;
                    rmadl++;
                }
                else if(g3l==g3r)
                {
                    manudd++;
                    rmadd++;
                }
                if(g4l>g4r)
                {
                    acmilw++;
                    lagall++;
                }
                else if(g4l<g4r)
                {
                    acmill++;
                    lagalw++;
                }
                else if(g4l==g4r)
                {
                    lagald++;
                    acmild++;
                }
            }
        }
        else if(counter==2)
        {
            for(round3=0;round3<=0;round3++)
            {
                cout<<"Los Angeles Galaxy "<<g5l<<"-"<<g5r<<" Real Madrid"<<endl;
                cout<<"AC Milan "<<g6l<<"-"<<g6r<<" Manchester United"<<endl<<endl;
                int manudgd = ((g1l+g3r+g6r)-(g1r+g3l+g6l));
                int rmadgd = ((g2l+g3l+g5r)-(g2r+g3r+g5l));
                int acmilgd = ((g2r+g4l+g6l)-(g2l+g4r+g6r));
                int lagalgd = ((g1r+g4r+g5l)-(g1l+g4l+g5r));
                if(g5l>g5r)
                {
                    lagalw++;
                    rmadl++;
                }
                else if(g5l<g5r)
                {
                    rmadw++;
                    lagall++;
                }
                else if(g5l==g5r)
                {
                    lagald++;
                    rmadd++;
                }
                if(g6l>g6r)
                {
                    acmilw++;
                    manudl++;
                }
                else if(g6l<g6r)
                {
                    acmill++;
                    manudw++;
                }
                else if(g6l==g6r)
                {
                    manudd++;
                    acmild++;
                }
            }
        }
        counter++;
    }
    while(counter!=4);
}

The line I got the error on was on the 74th line:

if(max(manudgd,rmadgd,lagalgd,acmilgd)==manudgd || max(manudgd,rmadgd,lagalgd,acmilgd)==rmadgd || max(manudgd,rmadgd,lagalgd,acmilgd)==lagalgd || max(manudgd,rmadgd,lagalgd,acmilgd)==acmilgd)

This was all in C++ just in case you don't see the tags or recognize the code.

max takes two arguments. You may want to see max_element. By the way, your code may need some refactoring - please read Clean Code from Robert C. Martin.

I have class with virtual init() function which is defined in derived class, and other function initializing this class and calling init function. How to name this other function?

I tried something like doInit but it looks like private function. init function name cannot be changed.

public:
bool myclass::this_other_function_init( params )
{
    systemInit(this);
    init();
    ...
    return true;
}
virtual init() = 0;

Private method naming convention - this topic shows great how to name private method, but now I have to do opposite name public method.

EDIT: how do you name your Initialization functions? init, initialize, start....etc ???

Naming is important. Right names are important but also coherence is important. Create your naming convention style and use it. I suggest you to read Clean Code. It explains well how to name your class and many other stuff to create code that explains itself.

Regarding your specific problem, two initialization are hard to understand As a user of our class, I don't understand why I must call two different initialization, because one must be sufficient, at usually is. I suggest you to implement all initialization code only in the derived virtual member. I suggest you some refactoring, or explain better what these functions do.

like my all teachers are saying " You can do everything because you can, but your code looks like a sh**"

So I was looking for some good tutorials on internet about Writing PHP code so clean as it's possible. I didn't find anything so I need your help. I need some url with tutorials about how to write clean php code. It can be BOOK as well!

I don't know what your teacher what meant but I'm pretty sure writing clean code is write code what make sense. What good write less if it's fucking hard to understand? For me, clean code doesn't mean syntax or less code only. Just write such that makes sense, use best practices and standards. It's a great start! Because you brought up on books, here's one of these:

Realated tags

.netabstractionaccess-specifieractionlisteneractiverecordagileandroidandroid-activityandroid-fragmentsandroid-navigationviewaplarchitectureargument-passingargumentsarraysasp.netasp.net-mvcasp.net-mvc-3asp.net-mvc-4assertautomated-testsawtbankbddbitmapblackberryboostcc#c#-2.0c#-4.0c++cakephpcakephp-1.3cakephp-2.0castingcheckboxclassclass-designcocoa-touchcode-conventionscode-designcode-metricscode-organizationcode-readabilitycode-reviewcode-smellcode-snippetscode-structurecodeignitercoding-stylecommentingcommentscompiler-constructioncompiler-optimizationcompositionconditional-statementsconstructorconventionscqrscudacustom-exceptionsdata-structuresdecompositiondeferreddefinitiondependency-injectiondesigndesign-patternsdesign-principlesdocstringdocumentationdomain-driven-designdrydtoduck-typingeclipseencapsulationentity-frameworkentity-framework-4.1enumserlangerror-handlingexcelexceptionexception-handlingextjsextreme-programmingfactory-patternfeedbackfile-organizationforeachformattingformsfunctionfunctional-programminggettergotogradlegrailsgraphguavahaskellhtmlhuman-readableideidiomaticif-statementimageimportincludeindentationinheritanceinlineinstanceinterfaceiosiphonejjavajavadocjavascriptjfreechartjgraphtjqueryjsonjson-apijunitlambdalanguage-agnosticlaravellaw-of-demeterlibgdxlines-of-codelinqlistlistfieldloopsmaintainabilitymatlabmemorymemory-managementmergemethod-signaturemethodsmockingmodelmodel-view-controllermodularizationmonadsmootoolsms-accessmultithreadingmvpmvvm-lightname-lengthnamesnamingnaming-conventionsnavigation-drawernestednode.jsnullnullableobjectobject-oriented-analysisobjective-coopopen-sourceoperator-overloadingoptimizationparameter-passingparametersperformanceperlphpphpdocpluginspocopremature-optimizationprintingprivate-methodsprogramming-languagesprojectproject-managementpromiseprotectedpythonpython-2.7rradio-buttonrdocreactjsreadabilityrefactoringreportrepository-patternresharperresourcesreturn-typereturn-valuerubyruby-on-railsscalabilityschemascopescrumselectorsemanticssettersilverlightsocketssoftware-designsoftware-engineeringsolid-principlesspecificationssqlsql-serverstandardsstatic-analysisstatic-methodsstlstructurestylecopsubmitswiftswingswitch-statementsyntaxtddterminologytestingtheorytry-with-resourcestypesunit-testinguser-defined-functionsuser-interfacevalidationvalue-objectsvariablesvb.netvbavisual-studiovisual-studio-2008visual-studio-2010visual-studio-2012web-applicationswildcardwpfxcode