Head First Object-Oriented Analysis and Design

Brett McLaughlin, Gary Pollice, David West

Mentioned 37

Provides information on analyzing, designing, and writing object-oriented software.

More on Amazon.com

Mentioned in questions and answers.

I'm a confused newbie and hobbyist programmer trying to get a grip on this, so forgive me if my question is a little off or doesn't make much sense.

I see a lot of questions on SO revolving around the use of design patterns, and I'm wondering if anyone has a good resources for learning about, and implementing design patterns? I understand the general idea, and know how/when to use a couple of them(Singletons, Factory methods) but I know I'm missing out.

(Just in case it matters, my language of preference is C# but I could learn from examples in other languages)

Applying UML and Patterns by Craig Larman. Start from the basic of analysis, design and uses a simple Case scenario. Introduces most of the basic patterns in a simple way.

An introductory book that I found useful and well written is Design Patterns Explained by Alan Shalloway and James Trott (Addison Wesley).

alt text

Do not start from the Gang of Four book, for it is not an introductory book by any means.

The original Design Patterns book is a must-read for all programmers.

It is an excellent book on every level: layout, clarity, insight, depth. It's one of those great books that you first read cover-to-cover, and then use as a reference until you literally know it inside out.

You could start by the Wikipedia page, but treat yourself with the great book too.

Design patterns are great for various reasons:

  1. gives you a starting for solving common problems.
  2. gives developers a vocabulary to talk about certain ways of solving problems in a very compact manner.
  3. when working with developers who know design patterns and you use design patterns in your solutions they will understand the solutions a lot faster.

But when your goal is just to learn design patterns I think you are missing the fundamentals. All design patterns are based on more common principles. High Cohesion, Low Coupling Open Closed Principle, DRY, Liskov Substitution Principle etc. For these fundamentals I would read the following books in this order:

  1. Head First Object-Oriented Analysis and Design (Head First) [ILLUSTRATED] (Paperback)
  2. Applying UML and Patterns (Hardcover)
  3. Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series) (Hardcover)

After that you are ready for the basic gang of four design patterns

  1. Head First Design Patterns (Head First) [ILLUSTRATED] (Paperback)
  2. The BIBLE
  3. A nice website (don't buy anything, it is not worth it) http://dofactory.com/Patterns/Patterns.aspx (some implementations of this site are worth a discussion

The next step:

  1. Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series) (Hardcover)
  2. The POSA books

And always remember : the pattern is not the goal !

Before spending money on books I would recommend Wikipedia's excellent design patterns page. Also for something different Google for "design pattern screencasts" or search for "design patterns" on YouTube. Getting the same information presented differently often helps the penny drop.

The Gang of Four book is the definitive text on the most well known patterns but is not that easy to read and with C++ examples not everyone's favourite.

The Head First Design Patterns text is far more accessible but only contains a subset of the Gang of Four patterns.

The most important thing is to understand where and why a particular pattern is useful. Afterwards search the web for implementation examples in the language of your choice and experiment until you "get it". Understand one pattern before moving on to the next. Everyone understands some patterns better than others (and there are hundreds of lesser known ones).

Just keep plugging away.

Head First Design Patterns

alt text

and the Design Pattern Wikipedia page are the best resources for beginners. FluffyCat is another good, free online resource for design patterns in both Java and PHP.

The Gang of Four book is where to go afterward, but it's fairly advanced, so I'd wait until you have a pretty firm grasp from the other resources.

I'd add that Design Patterns book from the "Gang of four" is a bible for anyone who is seriously interested in design patterns.

I have a problem. My mind isn't working as I wish it would.

I'm currently working on a small 2D game-engine in C++, but I am now facing a deamon - I suck at designing a 'system of classes' that actually works. There are a blockade in my mind that disables me from seeing where I should use a class and where I should not. I was reading an article about engine-design and it purposed to use a 'State' class to manage the state of different game entries (I was using an int). It also suggested that all objects for the game (not io/video/sound etc) derive from either Renderable or NonRenderable classes. That's smart. I already know that that was a smart way of doing it - I mean, every object in Java is of baseclass Object right? Smart, I know that! How come I didn't do it that way? What do I have to read to really get into this mindset?

Another example. I'm taking this summer-course in Ruby (really simple) and we're supposed to design a camping site. Simple! So, a camping is a collection of 'plots' that each have a electrical-gauge to measure how much power the guest has consumed. My design was three classes, one for a Camping - that in turn used arrays of Guest and Plot classes. My teacher suggested that I use more classes. WTF(!) was my first thought, where, what classes?? Everything was a class in my opinion - until I realized, maybe the gauge should be a class to? Right now the gauge was an Integer in the Plot class.

I want to learn how to come up with a object oriented solutions to my problems - not just how to make the most obvious stuff into classes!

Tips/books/articles/blogs?

Keep in mind, I'm not new to programing. I'm two years into a collage degree in CS and have been programming as a hobby for many years! I'm 'just' stuck - and it's preventing me from creating any larger piece of software!

Sorry for the wall of text. Thanks, much appreciated Andreas

Head First Object-Oriented Analysis and Design

I love Head First Books because they are fun to read. They have exercises and puzzles to scratch your head. I've read this book and found it very good.

The book covers:

  • Use OO principles (encapsulation and delegation)
  • Open-Closed Principle (OCP)
  • The Single Responsibility Principle (SRP)
  • Design patterns, UML, Use cases etc.

I probably learned most about object oriented software development from Craig Larman´s Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development.

In his approach, classes are derived in a systematic way from use cases:

  • Nouns in the use cases are mapped to classes,
  • verbs to methods and
  • adjectives to member variables.

This, of course, works better for notions in the problem domain than, say, GUI widgets. Nevertheless, starting with a description/use case of the program to be written helped me to find better abstractions than when I omitted that step.

For me OO didn't 'click' until I read a book about design patterns. If you're already comfortable with concepts like abstract classes, interfaces, etc that's only half the battle.

The next step is figuring out why you should prefer composition over inheritance, how to code to an interface and how to write your classes so that they are decoupled and well-encapsulated. Design patterns show you solutions to common OO problems and help you structure your code adhering to the above guidelines.

I can't recommend any particular books about C++ but the GOF book is the standard on Design Patterns (Java). I prefer books that talk about design patterns in a particular language so that you can get concrete code examples. Design Patterns In Ruby is pretty good, as is PHP: Objects, Patterns and Practice.

I get the feeling that your instructor doesn't particularly know what he's talking about. 'More classes' is pretty useless advice by itself.

In my opinion, one of the the best books I've read for learning object oriented concepts is:

The Object-Oriented Thought Process

For me, this book really gets you thinking in an object oriented way (well, the clue's in the title! :) It's fairly language agnostic, containing some small code samples throughout the text in VB.NET, C# and Java and frequently references many "greats" in the world of OO analysis and design, like Grady Booch, Martin Fowler and others.

Since the book helps you to think in an object oriented way, it'll often take a specific example and show the differences between the OO way of approaching a problem and the procedural way. This can be a big help if you're coming from more or a procedural background. It also touches on things like UML to help explain and understand the design behind complete libraries of classes (e.g. frameworks) and the interaction between classes and also the design of rich class hierarchies using concepts such as aggregation and composition.

Peter Coad and Ed Yourdon wrote a book about it couple years ago. While not filled with new overhyped methdologies, this book provides good foundation for thinking in object style.

I recently read an interesting comment on an OOP related question in which one user objected to creating a "Manager" class:

Please remove the word manager from your vocabulary when talking about class names. The name of the class should be descriptive of its' purpose. Manager is just another word for dumping ground. Any functionality will fit there. The word has been the cause of many extremely bad designs

This comment embodies my struggle to become a good object-oriented developer. I have been doing procedural code for a long time at an organization with only procedural coders. It seems like the main strategy behind the relatively little OO code we produce is to break the problem down into classes that are easily identifiable as discrete units and then put the left over/generalized bits in a "Manager" class.

How can I break my procedural habits (like the Manager class)? Most OO articles/books, etc. use examples of problems that are inherently easy to transform into object groups (e.g., Vehicle -> Car) and thus do not provide much guidance for breaking down more complex systems.

Becoming good at OO takes years of practice and study of good OO code, ideally with a mentor. Remember that OO is just one means to an end. That being said, here are some general guidelines that work for me:

  • Favor composition over inheritance. Read and re-read the first chapter of the GoF book.
  • Obey the Law of Demeter ("tell, don't ask")
  • Try to use inheritance only to achieve polymorphism. When you extend one class from another, do so with the idea that you'll be invoking the behavior of that class through a reference to the base class. ALL the public methods of the base class should make sense for the subclass.
  • Don't get hung up on modeling. Build a working prototype to inform your design.
  • Embrace refactoring. Read the first few chapters of Fowler's book.

Reading and then practicing OO principles is what works for me. Head First Object-Oriented Analysis & Design works you through examples to make a solution that is OO and then ways to make the solution better.

My eureka moment for understanding object-oriented design was when I read Eric Evans' book "Domain-Driven Design: Tackling Complexity in the Heart of Software". Or the "Domain Driven Design Quickly" mini-book (which is available online as a free PDF) if you are cheap or impatient. :)

Any time you have a "Manager" class or any static singleton instances, you are probably building a procedural design.

I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft. I've also been reading books on OOP. I'm coding a web-based database application at work. While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project. I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends. But that was a very linear approach to coding.

All this being said, something is just not clicking with me. I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding. I have to study other people's code so much that it simply seems like I'm not doing anything on my own. I'm getting discouraged.

It's not like I'm not capable of it. I picked up t-sql really quickly. Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want. SQL is something that I get. This isn't happening for me with OOP or C#. Granted, C# is inherently more complex, but at some point it has to click. Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add: A lot of the answers here were outstanding. However, one in particular seemed to have risen to the top and that's the one I marked as the "answer". I also hate not marking my questions with the answer.

I can totally sympathize. I have degrees in English and Film; the only programming I'd done before my latter twenties was on an Apply ][e, when I was 12. Classic ASP was my first foray into Web programming, which I only learned because I had to, as a technical writer working on an intranet project documenting real-estate software.

But eventually programming took, and I decided to start learning how to do things right. The transition wasn't easy. But I can say learning C# for Web development, particularly if you don't already sort of "grok" OO, can be daunting -- mainly because OO is so much about creating and managing state and statefulness, and the Web is inherently stateless.

Believe it or not, I learned more about OO writing Ajax apps with JavaScript and Flex apps in ActionScript -- i.e., building stateful clients -- than I ever did trying to force C# into my brain, because Ajax apps and Flex apps force you to think about things in terms of state. Returning to C# after having spent a couple of years (yes, a couple of years) writing lots of JavaScript code, and lots of Flex code, and reading lots and lots of both, was actually pretty easy, because by then, I realized how C# should work, as an OO language.

The Head First series of books is great, too -- people sort of downplay them around here, because they're rather silly, but they teach great concepts and I've been surprised how well their lessons have remained with me over the years. Try the OO title. And spend some time futzing around with JavaScript, too. Maybe have a look at Douglas Crockford's work. It'll click. Just give it some time.

I'm not sure whereabouts you are within your C# journey, but I certainly found Head First C# a very good read and use the mini projects therein as practice. As someone who had been studying C# in their spare time for around a year and a half prior to reading the book, it gave me some mini 'Aha' moments, for example, with delegates and callbacks.

Granted, some of the examples within it are contrived, much like many other programming books, but hey, who doesn't want to build their own Space Invaders?!

I am not that good at programming. I finished my masters degree in electronics. I want to learn C#, the .NET Framework, and SQL. How much time do you think it would take (if I have 5 hours a day to devote to it)? Also, what order do I learn them in? I have Visual Web Developer 2008, is that enough to begin?

Copied from a new question by the same user:
I should have specified that I wish to make a career out .NET Development. I'd like to give myself 2 months to get the 'basics' down. As a developer, what is expected out of you in IT companies? What skillset do they require and what are the responsibilities as a junior or mid-level developer? I don't have any industry experience, will I be able to get a feel of the job duties while at home?

All "relativity" aside, not fast. Based on the fact that you said you never programmed before...to become a basic programmer, a few years.

And to become a good to outstanding (using design patterns and industry recognized standards that relate to common standards as defined by ISO/IEC 9126 Standard such as testability, maintainability, etc.) programmer, it takes years of experience and coding often.. you do not become "Sr." or an "Architect" overnight and the same thing is true for a mid-level developer who doesn't code slop.

It's always a process where you improve. So learning is relative. But to learn the basics, seems simple until you start to design classes and interfaces. And even Leads stumble on the basics..doing things wrong. Everyone does. There is so much to be aware of.

If you're just going to be adding features (using classes your Lead or Architect has stubbed out for the team) and not really adding new classes, etc. it's easier....but you should take care in coding using standards and you still have to know complex areas of OOP. But that's not really OOP. When you start to creating classes, interfaces and knowing about inheritance, heap, references, etc. yada yada...and REALLY understanding it takes time no matter how smart you are or think you may be.

So, for a new programmer. Not easy. Be prepared to code a lot. And if you are not, find a job where you are. It's all about coding as much possible so you can get better.

Read these books FIRST. Do not dive into any others out there because they are not geared toward teaching you the language in a way you can get up to speed fast:

http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=pd_bbs_sr_4?ie=UTF8&s=books&qid=1231280335&sr=8-4

http://www.amazon.com/Head-First-SQL-Brain-Learners/dp/0596526849/ref=pd_bbs_sr_7?ie=UTF8&s=books&qid=1231280335&sr=8-7

http://www.amazon.com/Head-First-C-Brain-Friendly-Guides/dp/0596514824/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1231280393&sr=8-1

http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=pd_bbs_sr_3?ie=UTF8&s=books&qid=1231280393&sr=8-3

they will get you the fasted jump start into understanding, better than any books out there.

Also for these lame type of responses, ignore them:

"Then again, plenty of people (most normal people, non-programmers) never learn those subjects, so if you're like "most" people then the answer would be "it would take forever" or "it will never happen"."

Those come from developers (typically leads) who have some Ego trip that DON'T want you to learn. Everyone learns differently and at different paces and eventually you will become "fast". I get very tired of hearing Sr. developers say statements like this when their sh** also stinks many times no matter how good they are. Instead they should be helping the team to succeed and learn as long as their team is working hard to keep abreast and doing what they can on their own as well (not leachers).

Make sure you try to get a Jr. Level Developer position first...

I didn't find any question that would be this general.

Please post whatever you find to be a useful rule for oject-oriented design.

The best of OOP nothing, any approach that's fit for your project is best. But it is important what are OOP practices before choosing any/many from them for your project.

1: APIE: Abstraction, Polymorphism, Inheritance, Encapsulation.

2: SOLID Principle.

3: OO analysis and design.

4: Design patterns.

5: Code refactoring.

6: Effective Java.

I have recommended the Head First Design Patterns book many times.

It gives you a good intro to the GoF Design Patterns (a more advanced book that you also should read), but also a good intro to sound OOP design principles.

enter image description here

I've been studying OOP for quite a while now and I have a good grasp of the theory. I read the Head First book on OOP and, while it reinforced a lot of the theory, I found the case studies to be somewhat trivial.

I find that I'm applying OOP principles to my code each day, but I'm not sure if I'm applying them correctly. I need to get to the point where I am able to look at my code and know whether I'm using inheritance appropriately, whether my object is cohesive enough, etc.

Does anyone have any good recommendations (books, online guides, blogs, walk-throughs, etc.) for taking the next step in developing solid OOP skills?

I am working primarily in .NET (visual basic), but I welcome suggestions that incorporate various platforms.

Consider looking into Design Patterns. Although it seems like they aren't commonly used in enterprise applications (I've seen them more commonly used in API's and Frameworks than embedded into enterprise code), they could be applied to make software simpler or more robust in a lot of situations if only developers knew how to apply them.

The key is to understand the design patterns first, then with experience you'll learn how to apply them.

There is a Head First book on design patterns that teaches the concept pretty simply, although if you want a book that really covers design patterns in detail, check out the Gang of Four design patterns book, which is basically what made design patterns mainstream and is referred to almost every time the topic is brought up.

Design patterns can be applied in pretty much any object-oriented language to some degree or another, although some patterns can be overkill or over engineering in some cases.

EDIT:
I also want to add, you should check out the book Code Complete 2. It's a very influential book in the world of software development. It covers a lot of different concepts and theories. I learn something new every time I read it. It's such a good book that if I read it every 6 months to a year, I look at it from a different perspective that makes me a better programmer just by re-reading it. No matter how much you might think you know, this book will make you realize just how little you really know. It's really a great book. I can't stress how much you should own this book.

Read Refactoring by Martin Fowler, and apply it to your own work.

It will take you through a litany of malodorous characteristics of software code that describe how to detect improperly constructed classes, and even more importantly, how to fix them.

I am currently half-way through the following book:

http://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062

I cannot recommend this book strongly enough in terms of learning a real-life, professional-grade, practical approach to drafting and applying a well-formed and iterative design strategy before diving into code.

I, too, read the "Head First" book and felt that I was much better off for having read it.

After having a few years of working-world experience, I now view the Craig Larman book that I am recommending to be a perfect "next step" for me.

About the Presence of "UML" in this Book Title:

Whether you have positive feelings or negative feelings about UML notation, please do not let that influence your decision to buy the book (ISBN 0131489062) in either direction.

The prominence of "UML" in the title is misleading. While the author does use and explain UML notation, these explanations are extremely well-woven into relevant design discussions, and at no time does this book read like a boring UML spec.

In fact, here is a quote taken directly from the book:

What's important is knowing how to think and design in objects, which is a very different and much more valuable skill than knowing UML notation. While drawing a diagram, we need to answer key questions: What are the responsibilities of the object? Who does it collaborate with? What design patterns should be applied? Far more important than knowing the difference between UML 1.4 and 2.0 !

This book at times seems like it is "speaking to" a lead architect or a project manager. What I mean to say by that is that it assumes that the reader has significant control over the planning and direction of a software project.

Nonetheless, even if you are only responsible for some very small piece of your company's projects and products, I would still recommend this book and encourage you to apply some "scaled down" modifications of the book's advice to your piece of the project.

Tortoise HG is extrodanarily well designed piece of OO open source software (written in Python).

If you already understand the basics, building something from scratch in a fully object oriented language will be a good step in fully understanding OOP software architecture. If you don't know Python, Python Essential Reference will take you through the language in full in a few days to a week.

After you understand the language take a look through the software above and you'll have all sorts of epiphanies.

I keep hearing the term object has behavior and state or just one of them. But what is the difference or what does it mean, and if anyone can give an example I would really appreciate it.

class Door {
  boolean isOpen;

  void close(){
    isOpen = false;
  }
}

Look at this simple snippet. We have class Door, it has a state isOpen - variable describes current state of this door. Method close it is behaviour of door, when we call it, we change current state of object.

I advice you to read good for beginners book about object oriented programming: Head First Object-Oriented Analysis and Design. If you read it you get better understanding.

I understand procedural programming (well, who doesnt) and want to get a good understanding of OOP and after that functional. I'm just a hobbyist so it will take me an age and a day, but its fun.

Does anyone have any ideas for what I can do to help? Project ideas? Example well documented code thats out their?

I am currently using C++ but C# looks a lot nicer to work with.

I'd recommend working mainly with a strongly-typed language like C# or Java, as so many of the design patterns and general OOP principles are geared towards strong typing (GOF, Refactoring, Uncle Bob). Ruby is wonderful but a lot of common OOP principles like coding to interfaces won't apply.

Spend some time with Uncle Bob's SOLID principles. Go slowly, paying particular attention to Single Responsibility. If you don't get anything else from Uncle Bob, get SRP in your head and apply it early and often.

I also like Uncle Bob's idea of code katas. I'd recommend working through the bowling game kata.

There are some great OOP books from Head First covering Object-Oriented Analysis and Design and Object-Oriented Design Patterns.

I recommend you read Object Thinking by David West. There is very little code in the book, but a lot of talk about how to model.

A couple things I wish someone would have told me when I was starting out are:

  1. When modeling objects, you should focus on behaviors more than the shape of the data.
  2. Although many OO tutorials model real world things such as animals and vehicles, many of the things we model in OO software are concepts and constructs (things that have no physical representation in the real world).

Q1. In my university studies of object-oriented modelling and design they recommend thinking about what an object can do for its method, and what its responsibilities are for its attributes. All attempts at clarification have resulted in further confusion.

This tends to generate a class diagram with actors who have all the actions, and inner classes which only hold data.

This doesn't seem correct. Is there another way of thinking about how to model the objects?

Q2. Also, the course seems to emphasize modelling the objects after their real-world counterparts but it doesn't necessarily make sense in the domain model. IE. In a medical practice, they have Patient: CreateAppointment(), CancelAppointment() but that is not how it would be implemented (you would modify a the appointment collection instead). Is there another way of thinking about this?

Example Q1

Secretary: RecordAppointment(), RecordAppointmentCancellation()

Appointment: time, date,... (no methods)

Example Q2

Doctor: SeePatient()

While SeePatient is a use-case, it does not make sense for a method on the actual class. How do you think about this?

Unfortunately, the roadblock you've hit is all too typical in academia. Academic projects tend to start with video rental stores, libraries or student registration systems (yours is a variance of this with a doctor's office) and then inheritance is taught with animals. The guideline you've provided is also very typical

they recommend thinking about what an object can do for its method, and what its responsibilities are for its attributes

In fact when beginners ask I usually explain an object's property's are the things it knows about itself and its methods are the things it knows how to do. Which is really just another way of saying exactly what you have there. As you've discovered this way of thinking quickly breaks down when you start discussing more tangible systems and not just examples.

For instance the guideline works pretty well with this object:

public class Tree
{
    public int Height { get; set; }
    public void Grow(int byHowMuch)
    {
        Height += byHowMuch;
    }
}

While this certainly fits the bill your right to think that it doesn't "feel" right:

public class Secretary
{
    public void MakeAppoinment(Patient patient)
    {
        //make the appointment
    }
}

So what's the solution? It's a matter of taking what you are being taught and applying it. Learning and understanding design patterns will help a lot with developing systems which are more functional than a tree that knows how to grow.

Recommended reading:

To solve the issue you're been presented I would probably use a combination of inherited person classes and interfaces, which would perform their actions through a series of service classes. Essentially a secretary, doctor, and patient would all inherit from person and each of these classes could be passed to accompanying service classes. The service classes may or may not do things like SeePatient(). Please don't take this example to mean that person classes wouldn't have methods.

Stack Overflow has more than a few related questions which may be of use:

Additionally, it would be good to check out:

Finally, there isn't a single definition of what makes an application object oriented. How you apply patterns, principles etc. will define your program. The fact that you are asking yourself these questions shows that you are on the right track.

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 trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some global variables and with a bunch of functions. I can't figure out if this design can be improved by creating a number of classes to encapsulate some of the data and functions and, if so, how to change the design.

My data is basically a list of accounts ['checking', 'saving', 'Amex'], a list of categories ['food', 'shelter', 'transportation'] and lists of dicts that represent transactions [{'date':xyz, 'cat':xyz, 'amount':xyz, 'description':xzy]. Each account has an associated list of dicts.

I then have functions at the account level (create-acct(), display-all-accts(), etc.) and the transaction level (display-entries-in-account(), enter-a-transaction(), edit-a-transaction(), display-entries-between-dates(), etc.)

The user sees a list of accounts, then can choose an account and see the underlying transactions, with ability to add, delete, edit, etc. the accounts and transactions.

I currently implement everything in one large class, so that I can use self.variable throughout, rather than explicit globals.

In short, I'm trying to figure out if re-organizing this into some classes would be useful and, if so, how to design those classes. I've read some oop books (most recently Object-Oriented Thought Process). I like to think my existing design is readable and does not repeat itself.

Any suggestions would be appreciated.

Not a direct answer to your question but O'Reilly's Head First Object-Oriented Analysis and Design is an excellent place to start.

Followed by Head First Design Patterns

I have two professional programmer friends who are going to teach me, and they both love the language (C#). I know that their specific skills and enthusiasm more than out-weigh any drawbacks to the language, but they seem like such fanboys I'm left wondering what the catch is.

I only have experience of XHTML and CSS, so accept that getting my head around Object orientation will be a challenge, for example. I'm vaguely aware that some languages (python?) allow you to test small sections alone, and that this is particularly useful for beginners. I worry that I'm trying to run before I can walk by going straight for C#.

I'm sorry this is a bit of a rambling question, but advice would be greatly appreciated.

I recommend the Head First Series: Head First C# available at Amazon.com. They do a pretty good job explaining Object Oriented (OO) principles but you also may want to check out a dedicated (OO) book. Head First also makes a decent OO design book: Head First Object-Oriented Analysis and Design available at Amazon.com.

I'm looking for some good courses on object oriented programming. I've been programming for about 4 years so far, but I don't feel like I have a SOLID grasp on OO.

How did you learn?

Maybe you'll like the "Head First" approach.

I'm looking for some visuals for a presentation to illustrate the principles of oop in a simple-to-grasp way.

I want to avoid saying stuff like "an object is a software bundle of related state and behavior".

Has anyone seen a non-jargon-y illustrated guide to OOP?

The illustrations in Grady Booch's book Object Oriented Analysis & Design with Applications are pretty good , and quite funny!

O'Reilly's book Head First Object-Oriented Analysis and Design may fullfil your needs

Good morning everyone,

I hope I'm not posting this in the wrong place; I've been programming web projects, mostly in MVC and ASP.NET for consulting companies, but I always pick-up unfinished projects, so I gotta say, my experience in web development isn't as good as I'd like it to be. To improve my experience, I decided to accept building a project for a veterinarian clinic and I'm going to build the project in MVC. There are a few things I'd like to know to make my project well structured and to avoid feeling lost in the process because I don't have as much time to research as I'd like to. So the main questions I'd like to ask are:

  • When beginning a new project, where should I begin? Making the stylesheets? Should I go straight for the code? If I make some planning, how should I go about it then?

  • When building up the Media folder in my project, if I decide I'll use
    jQuery and the like, what files
    should I really get? What's the best way to implement jQuery in a MVC
    project without having to mention it in every page?

  • To make a sort of planning for
    myself, complete with deadlines I
    have to respect, what structure
    should I use?

  • Well, I'm not good at designing at
    all, and I often have to rely on
    other people's CSS to make things
    look decent, so how could I use this project to improve that and still
    make it look good?

I hope we can all share some experience in the matter at hand and make this topic help others who might be feeling the same weaknesses as I do.

When you start building your code I suggest you start with register, login and authentication. After that: Internationalization and localization (see: http://en.wikipedia.org/wiki/Internationalization_and_localization)

Then create your CRUD's and so on..

EDIT: Some other resources you might wanna have a look at:

Good luck!!

I am a total beginner and would like to eventually learn to develop for the iphone.

I have just done a beginner's CS course where the language we learned was JavaScript. We studied basic concepts like: variables, arrays, loops (for,while,if,if..else..), properties and functions.

I'm wondering if I am starting in the right/wrong place by following this book: Learn C on the Mac by Dave Mark?

I have read a few chapters and am finding it a bit hard to get my head around the way that C works, for example the way that Strings are printed seems overly complicated as compared to JS.

Do you think that JS was the wrong language to start off with and would I be better to go from JS straight to Objective-C rather than to C?

I have tried to read up on previous threads on the merits/demerits of learning C first but haven't found any that relate JS to learning C/Obj C/ Cocoa.

Any advice appreciated as I am very new to this.

Thanks

Yikes.

JavaScript seems like a really poor choice for starting a new developer off on the right path. It has the basic constructs of most languages, but weak typing and the Prototype approach to Object Oriented development would be hard to transition away from.

That said, I would first pick up a book on straight Object Oriented programming concepts first. Head First Object-Oriented Analysis and Design seems to be a popular choice around here.

After that, I'd go straight to Obj-C. You'll pick up the pieces you need from C without learning any of the potential bad habits that people sometimes bring wit them from a procedural language like C to an Object Oriented language like Obj-C.

I hope this is the right place to ask.

I am fairly new to .NET and I am having some problems regarding implementing OOP concepts. I have followed a couple of books about c# and here is he problem.

By now, I know the OOP concepts theoretically, but I donot know 'How and When' to use these concepts in real world scenario. e.g. i know the DEFINITION of abstract, sealed, public classes and so on but i donot know WHEN to use them.

every books talks about person class or car class examples. but all those examples doesnt seem to work if i think of creating a for example simple inventory system. how would i define classes, methods, properties about an inventory system. this is where i alwys get stuck.

If possible please tell me of some book or resource to follow.

Thanks

You might like to read Ron Jeffries' Extreme Programming Adventures in C#. It's rather outdated in terms of C# versions, but it's a good read. It is essentially his diary of learning C# by writing an XML editor. It is also focused on XP methodologies, as indicated by the title, especially test-driven development.

By presenting the material in the form of a journal or diary, the author gives interesting insights into his thought processes; the flow of the narrative depicts his problem-solving process (pursuing a solution, then realizing it's no good, abandoning it for another solution, etc.).

That aspect is usually absent from programming books, which generally lay out ready-made solutions, sometimes without adequately explaining the problem being solved. In real life, problems come before solutions, not the other way around.

there are tons of books out there teaching you a new language. but some of them are just too thick with lot of information and less code. it usually makes you sleepy. especially when you already know the basic syntax and wanna learn how to use a new language very fast.

are there good series of books for this?

the dummies series is very good but are there like "faster" book series that skip the unnecassary (how do you spell it) talking and get straight to the point?

maybe from 500 pages to 150 hard core practical step to step with pics kind of pages=)

these kind of series would be very appreciated i think (lynda is good cause its that fast to learn a new language! but unfortunately they dont have java videos)

For Java, yes, the head first series as others have suggsted. That is my favorite series of books. I've read over 2 of them and both were great. As well as the Java one, you should also get the OOD one: http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=sr_1_1?ie=UTF8&s=books&qid=1263239109&sr=8-1 Object Oriented design is at the heart of learning Java.

Also, if you want to go a little cheaper, the Java tutorial is excellent IMO. There is a lot of meat there and its defiantly fast and easy to progress through. Check it out here: http://java.sun.com/docs/books/tutorial/ Go down to the section header "Trails Covering the Basics" and start there.

The team is familiar with ASP.NET and has been working in VB.NET for several years, but they just haven't made the transition in thinking in terms of objects. In fact, they may be a little intimidated by OOP from brief glimpses they've seen of C++ and unmanaged environments. Work has kept them busy enough that they haven't had time to properly absorb the benefits that .NET and OOP provides.

I'm looking for some lightweight resources (i.e.: blog posts, articles) that I can share with both developers and/or managers which would help to introduce the object oriented paradigm in a nicely presented fashon. The language could be in either C# or VB.NET, though VB.NET would be preferred.

Thanks!

Head First Object-Oriented Programming from O'Reilly & Associates by McLaughlin, et al.

Here's a link for more: Head First OOAD

Great book. Great series. Easy to read and easy to grasp the concepts of OO, which is what you're after with your team.

Head First OOAD Book Cover

For OOP with VB...

Beginning Object-Oriented Programming with VB.Net

Object-Oriented Programming with Visual Basic .Net

Depending on how experienced one is you may want to also read about Object-Oriented Analysis and Design. These will help you to wrap your head around how to do it.

Head First Object-Oriented Analysis and Design

Object-Oriented Analysis and Design with Applications

MS article on OO in VB.Net:

http://msdn.microsoft.com/en-us/library/aa289512(VS.71).aspx

A little old but gives the basics....

It has been my experience that depending on how entrenched the team is on the event driven model will greatly influence how effective the team moves/embraces OO. It's easier than I would like to admit to just use objects in .Net and not really understand OO. Coming from VB6 it was too easy to keep on trucking the classic way. The OOA & OOD books may be a great starting point if your team seems to be just "users" of the objects in .Net versus actually creating classes in their own code.

What is the best way to identify the objects and their Relationship between them ? As i am new to Programming[c# windows application],I am finding difficult in making relationship between objects . Can anyone suggest me the best way to start with?

Thanks, Karthik

You should probably read up on object oriented programming and design. Then read up on C# programming.

Here are a few book suggestions:

Then when you're ready, you can move on to Jon Skeet's book =)

If you're not looking to purchase a book, maybe take a look at this site. It covers key object oriented design principles.

Im a newbie PHP programmer and I have a few questions about creating a REST based API service.

Basically, its going to be a github open source project which is going to scrape various data off the web and offer it as an API in XML. Now here are my questions in terms of how should I or how can I do this.

1) Since there isnt a robust/same pattern for getting various data through scraping, what is the best way to actually output the xml?
I mean the PHP file would have various lines of extracting data from various points in the code and the file would be a lot of lines. Is it a good idea to type the code to output the result in there?

2) Is there a way to organize the scraping code in a sort of class?
I cant think of a way that would work besides linear approach where not even a function is created and you just apply functions (in general).

3) If theres a way to do that ^^ , how can it you output it?
Is there any other approach besides using another file and getting the contents from the main file and displaying the code through the secondary file.

4) If I were to offer the API in XML and JSON, is there a way to port from one result to another or will I have to manually create the fields in json or xml and place the content in there?

I might have more questions that might arise after these have been answered but I hope I get everything cleared up. Also, this is assuming that the results are not fetched from a DB so the data has to be scraped/tabulated on every request. (even though caching will be implemented later)

Thanks

This question is probably more appropriate on http://codereview.stackexchange.com/

Not to be rude, but a newbie programmer developing an API is like a first-year med student offering to do open-heart transplants for free. I understand that you believe that you can program, but if you intend to release publicly accessible code, you probably need more experience. Otherwise guys like me will muck through it and file bug reports ridiculing your code.

That said, if you want theory of good API design you should probably check out Head First Object Oriented Analysis and Design. You'll want to focus on these key concepts

  1. Program to an Interface, not an Implementation
  2. Encapsulate what varies

...and follow other good design principles.

...honestly, there's a lot to cover to good interface and good systems design. You can use this as a learning exercise, but let people know they shouldn't rely on your code. Though they should know that screen scraping is far more brittle and instable than web service API requests anyway, but many don't.

That said, to provide some initial guidance:

  1. Yes, use OOP. Encapsulate the part that actually does the scraping (presumably using cURL) in a class. This will allow you to switch scraping engines transparently to the end user. Encapsulate your outputs in classes, which will allow for easy extension (i.e. if JSON output is in a Single Responsibility class and XML Output is in another, I can add RSS Output easily by making a new class without breaking your old code)
  2. Think about the contracts your code must live up to. That will drive the interface. If you are scraping a particular type of data (say, sports scores for a given day), those should drive the types of operations available (i.e. function getSportsScoresForDate(date toGet))
  3. Start with your most abstract/general operations at a top level interface, then use other interfaces that extend that interface. This allows users to have interfaces at different levels of granularity (i.e. class SensorDataInterface has a method getData(). HeartRateMonitorInterface extends SensorDataInterface and adds getDataForTimeInterval())

I'm looking for a video tutorial/training or even lectures on Object Oriented Analysis & Design. I don't need explanation for UML and Use cases. I want a full software life cycle explained.

I already read Head First: Object Oriented Analysis & Design

The book actually had all I was looking for:

Requirement gathering, Use case diagrams, Class diagrams all applied to a real project.

I'm looking for something similar in which all these topics are explained practically of a real life full project.

youtube has a video - lecture 9 and 10 http://www.youtube.com/watch?v=uH7wh9f2hyo will cover aspects of OOAD.

But u better read a uml book or Fowlers site on uml - http://martinfowler.com/bliki/uml.html

Hope I helped you.

I've been reading and learning about Object-Oriented programming (Head First Object-Oriented Analysis and Design and Code Complete: A Practical Handbook of Software Construction – thanks to suggestions found on StackOverflow). I've also been learning how to use a couple PHP MVC frameworks (specifically Codeigniter and Kohana).

Some of the principals of Object-Oriented that I've read about are handled differently by the MVC frameworks. I think I've managed to understand the differences and why the decisions were made (complete and easy to use solution), but I wanted to test my assumptions...so if you'll humour me...please comment or correct.

Assumption #1:

Thinking about the right abstraction for a web application, the directory containing the library of classes should be located outside of the directory containing the presentation files. This organization adheres to the DRY ("Don't Repeat Yourself") principal allowing for multiple presentation folders (www.domain.com, management.domain.com, api.domain.com, etc.) to work with the same objects.

Assumption #2:

If all your classes are located outside of your presentation folders, then the models in your MVC implementation just use instances of those classes. If that's true, then the MVC framework is just a presentation class (the controller) that helps to manage the input (GET & POST requests), the response (models or instances) and output (views or templates).

Assumption #3:

If the MVC framework is just a presentation class, then the database class that the controller instance initializes breaks the abstraction of the controller class. A model (of the controller instance) shouldn't have a ("has a") database, it should have a thing (user, product) from the library of classes and that thing should have a database.

Assumption #4:

Furthermore, if the MVC framework is just a presentation class, the database class that the controller instance initializes is too tightly coupled with the controller class. Changing from one method of storage to another requires re-factoring of all the models.

Assumption #5:

With a HMVC framework, the issues with the controller containing the database is worse, because your models are more module (more models, more re-factoring).

UPDATE:

Sorry, I may have used the terms controller and model a little loosely...maybe that speaks to the tight coupling. The source of my confusion stems from the database class syntax.

With a model, shouldn't it be:

$user = new User($id);
$data['name'] = $user->getName();
$data['title'] = $user->getTitle();
return $data

Instead of:

$query = $this->db->get_where('user', array('id' => $id), 1, 0);
$row = $query->row_array(); 
$data['name'] = $row['name'];
$data['title'] = $row['title'];
return $data

Can u give a real sample scenario using OOP structure for developing programs.

Would appreciate your response.

Thank you,

OOP principle - program to interfaces

What does "program to interfaces, not implementations" mean?

For more of OOAD, read this book. It explains majority OOAD principles and techniques very well.

alt text

(Nothing serious in this question)

Ones a time I've read such an example of "bad application architecture":

There was a "rendering application" (browser, as far as I remember), so it was told, that having "render()" method in TagA, TagUL, TagDIV classes is really bad practice, because you'll have lots of "render-code" smeared all around. So (in this example), they adviced to have RenderA, RenderUL, RenderDIV classes that would implement rendering. And tag-objects would incapsulate those renderers.

I can't understand why that's a bad practice. In this case we'll have lot's of render code smeared around Render-* objects. And, finaly, why not to have Redner-singleton with lot's of overriden methods? That sounds, at least, cheaper.

What to read to understand it better?

Will the rendering for all of these different objects be the same? If so, then it should only be implemented once, most likely in a base class. This would be a better solution than a Singleton, which serves a completely different purpose: mainly to implement a resource (notice its a resource, not a method) that should only exist once.

If each implementation of render() will be different (which is most likely the case) then there is nothing wrong with them being implemented in separate objects, this is called polymorphism. What should probably be done though, is to have a class hierarchy in which the render() method is defined in the base class (most likely as abstract) and implemented in the derived classes. This effectively formalizes the interface, meaning that any class that inherits from said base class will have the render() method available and will have to implement it.

If you have parts of the render code that are common, and parts that are specific to the derived classes, instead of having to duplicate the common parts in all the derived class implementations, you can use a Template Method pattern, whereby the base class method does the common parts, and orchestrates calling the derived class implementation(s). Here is a pseudo-code example in C++

class TagBase {
public:
    void render() {
        // do some common stuff here
        doRender();
        // do some more common stuff here
    }

    virtual void doRender() = 0;
    ....
};

class TagA : public TagBase {
public:
    virtual void doRender() {
        // do your specific stuff here
    }
};

Here are a few good books:

For some time now I am trying to figure out how I can refactor some of my code to reduce redundancy throughout my application. I am just learning the basics of OOP and can create simple classes and methods but my knowledge is limited in terms of practical applicability. The following bit of code illustrates my frustration:

#region DELETE selected users - button

protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
    try
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("chkRows");
            if (cb != null && cb.Checked)
            {
                // get the row index values (DataKeyNames) and assign them to variable
                string userName = GridView1.DataKeys[row.RowIndex].Value.ToString();

                // delete selected users and their profiles
                ProfileManager.DeleteProfile(userName);
                Membership.DeleteUser(userName);

                Msg.Text = "User(s) were sucessfully <b>DELETED</b>!";
                Msg.Visible = true;
            }
        }
    }
    catch (Exception ex)
    {
        Msg.Text = "Oops! " + ex.Message;
        Msg.Visible = true;
    }
    finally
    {
        // refresh gridview to reflect changes
        GridView1.DataBind();
    }
}

#endregion

This bit of code is used on several pages of my project in the pages codebehind file. How can I move this to a class file. I don't know how to reference an object like a gridview in a class because it does not exist like it does on the actual page.

Could some one help out please? Thank you.

There are many principles that you generally apply when trying to refactor code. Currently, you're trying to refactor your code as to not violoate the DRY principle (DRY = don't repeat yourself). It would be a great move to refactor that code.

But, some other principals might come in to play that you might want to consider. The single responsibility principle would suggest that each method does only one unambiguous thing. Think about the operations your current method does. It extracts the usernames from the GridView, and then deletes some data associated with that user. That might be better off as two methods.

Also, loosely coupled code is good. You don't want a bunch of dependencies between your classes. For example, if you moved your whole method, as is, to a separate class or library, that class or library would be dependent on the ASP.NET libraries, because it makes a specific reference to the GridView control. But it doesn't need to. You could have a separate method that pulls the username out of the GridView (this method would be tightly coupled with ASP.NET), and then a separate one that does the rest of your actions (such as deleting the user's data), which only requires the username. That second method would not be coupled to ASP.NET in any way. So by having separate methods that each have a single responsibility, you'll have more loosely coupled code. Two for one.

As for what you said here:

I don't know how to reference an object like a gridview in a class because it does not exist like it does on the actual page.

You'd just want to pass a reference to your GridView when you call the method that would extract the usernames. Something like this:

public static class Util
{
    public static IEnumerable<string> GetUsernames(GridView gv)
    {
        List<string> userNames = new List<string>();
        foreach (GridViewRow row in gv.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("chkRows");
            if (cb != null && cb.Checked)
            {
                // get the row index values (DataKeyNames) and assign them to variable
                string userName = gv.DataKeys[row.RowIndex].Value.ToString();
                userNames.Add(userName);
            }
        }
        return userNames;
    }
}

Now, in any of your asp.net code behind pages, you can do:

IEnumerable<string> usernames = Util.GetUsernames(GridView1);
foreach(string username in usernames)
    doSomething(username);

The doSomething(username) would be a call to some other method that does your delete operations, or whatever you want.

Hope this helps.

Oh, and if you're just learning the basics of OOP, I would recommend something like Head First Object-Oriented Analysis and Design, or any book that seems to adequately cover the subject. I like the O'Reilly Head First series. The information is very digestible.

I am a newbie in OOP and "design" / "architecture". I have a class that works with a Crawler object (the result of a GET request using Goutte) in order to figure out if various elements are present in a page.

It has methods like isHtml5 or getAnalyticsCode.

In order to give more user-friendly notifications, I've set, within each method, a notification message explaining the outcome of the check.

For example, if the doctype is not HTML5, then within isHtml5 is have something like this: $this->setNotification('Page is not HTML5').

I retrieve the notifications progressively for display in the view within a Controller.

The more I think about this class, the more it seems to me that those notifications don't belong there. But I don't know where to put them.

I thought about the Controller but if I want to use other Adapters, ie. Command line or an API, then I will have a duplication of those notifications through all the apdaters. But maybe it is not so bad... (I'm also confused about possible translations of those notifications and how to do that, but I'm far from being there in the design so far).

Any ideas or suggestions? Resources I should have a look at? If possible, I'd appreciate something quite "simple", so that I can have clean code and so that I don't get lost too much to begin with (I already have a tendency to overcomplicate things... ^^).

Thanks in advance.

There can be many ways in which a solution can be designed, and all of them can be considered good. Depending upon the requirement, sometimes simple (and logically sound) but not so good designs can be better than very complex (overworked) designs.

I would strongly recommend Headfirst OO Design. I think it is a good resource for intermediate/advanced level.

As far as your current problem is concerned, I think following design can be a good candidate.

A Notification Class: //Depending upon implementation, This can be private to notification service class

private notificationType;
private notificationMessage;
private notificationPriority;
//Or just the message
//All Getters and Setters

A NotificationService class:
private List<Notification> notifications; //Can be LinkedList 
static getInstance();

// To create and add notification to list
public void addNotification(String msg); // Can have other items too..

//get the copy of list for printing or other purposes
public List getNotifications();

This is not complex. Again, design depends upon your problem domain. Same thing can also be done by creating a Notification interface, then creating various classes implementing that interface - for each notification type, and a main manager/service class handling everything.

As you "have a tendency to overcomplicate things...", its always better to have a design where nothing can be deleted.

I am currently doing a uni assignment as a fresher so I'm not very experienced with coding.

The assignment is to allow the user to create a class diagram. Currently I have a secondary frame that the user inputs a UML design of the class in a JTextArea and then this should be passed through to my GUI by taking what the user wrote and drawing the string (drawString) onto the created class.

Currently I am getting a nullpointerexception when trying to get the String from the JTextArea to drawString and I don't understand this because surely inputUML.getText() would be a String so should be able to be passed through?

This is the class that I am trying to pass the string into

package main;
import java.awt.*;
import javax.swing.*;
import classdesign.ClassCreation;



public class GroupCreateClass {
private double x;
private double y;
private double r;
private String message;
private String classdesign;


public GroupCreateClass(double x, double y, double r) {
    this.x = x;
    this.y = y;
    this.r = r;
}

public void draw(Graphics g) {
    makeRectangles(g);
    deleteBox(g);
    userdesignofclass(g);
}

public void makeRectangles(Graphics g) {

        g.drawRect((int)Math.round(x-r),(int)Math.round(y-r),
            (int)Math.round(325.0*r),(int)Math.round(350.0*r));

        g.drawRect((int)Math.round(x-r),(int)Math.round(y-r),
            (int)Math.round(325.0*r),(int)Math.round(19.5*r));

}

public void deleteBox(Graphics g) {

        g.fillRect((int)Math.round(x-r),(int)Math.round(y-r),
            (int)Math.round(19.5*r),(int)Math.round(19.5*r));
}

public void userdesignofclass(Graphics g){

    message = new String("Class");
    g.drawString(message,(int)Math.round(x+140),(int)Math.round(y+15));

    classdesign = (String.valueOf(inputUML.getText())); // This is the code that is giving me a nullpointerexception. I don't understand why, as surely inputUML.getText() should be a String...?
    g.drawString(classdesign,(int)Math.round(x+200), (int)Math.round(y+15));//
}


public double distanceTo(double x, double y) {
    return (Math.abs(this.x-x) + Math.abs(this.y-y));
}

public void update(double x, double y) {
    this.x = x;
    this.y = y;
}


}

This is the class that has the JTextArea, it is in another class and package, but the class that should be retrieving the string Extends this class.

 package classdesign;
 import java.awt.*;

 import javax.swing.*;

 public class ClassCreation extends JFrame {

private JFrame frame;
private JLabel instructionlabel;
protected JTextArea inputUML; //This is the JTextArea containing the text that I am trying to pass through.
private JButton create;

public void initGUI(){

   frame = new JFrame();
   frame.setSize(325, 350);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setTitle("Class Design - Fill in Class UML");

   JPanel CreationPanel = new JPanel();
   CreationPanel.setLayout(new BorderLayout());

   inputUML = new JTextArea("Write UML here");
   inputUML.setLineWrap(true);
   inputUML.setWrapStyleWord(true);
   CreationPanel.add(new JScrollPane(inputUML),BorderLayout.CENTER);
   CreationPanel.add(inputUML,BorderLayout.CENTER);

   Create = new JButton("Create Class");
   CreationPanel.add(Create,BorderLayout.SOUTH);
   //Create.addActionListener(this);


   frame.add(CreationPanel);
 }

 public Frame getFrame() {
       return frame;
   }



 }

So what I want to know, simply, is how I can fix that, is there just a line I'm going wrong? or do I have a massive logic problem in what I'm trying to achieve?

Thanks :)

The simple answer to your question is that it's quite possible you haven't instantiated inputUML [ostensibly by calling initGUI()] before calling strings() [which is a terrible name for a method].

But your problems go far deeper than this. This use of inheritance is completely wrong. Favor composition over inheritance. The use of Magic Numbers is not recommended. The variable names are poor (Java is case sensitive, btw. uml is not the same as UML)...do yourself a favor and start browsing Head First Java and Head First Object Oriented Analysis and Design. Also consider Test Driven Development by Example I know you think you don't have the time, but it's much harder to unlearn bad habits than take a little extra time at the beginning to build good ones.

I know that my this question may sound pathetic to you but as a beginner in .NET, it means a lot to me.

I just want to know that how can I utilize the concept of Abstract class, virtual class etc. in my shopping cart website. I have read the tutorial out there on internet and I saw some examples too, but those examples are so general that they dosen't fit into real world scenerio like I am searching for a shopping website. Same questions again and again comes to my mind that why to made a class only to give the declaration of methods and property.

I understand that most of you are Gurus of .NET and have ample knowlesge in it but if you could just help me out in thinking the logic behind this i'll be very greatfull.

If possible, please recommend me nice books for asp.net design patterns, from which I can learn design patterns.

Thanks in advance

Your one stop resource and guide is Head First - OOAD.

alt text

I started writing some code for a 2D game, created a class "objets" trying to keep it as generic as possible. I have a few methods and attributes that are common to every kind of element (buldings, ppl, interface buttons, etc) like (w, h, x, y ...you know) but most of them only make sense when applied to and specific type of item. So I would have to inherit a new class for every type of actor in the game? Just wondering if this is a common practice, or maybe i should manage it in a different way.

Thanks in advance.

It sounds like you are over-using inheritance. It is certainly a red flag when you simultaneously say "common attributes like ..." and "...only make sense when applied to a specific type." Also, it is a red flag that domain objects such as building share a common base class with an interface object like button. Finally, it is quite unusual to define your own objet (object?) class from which every class in your system derives. It's not inconceivable, but in combination with your other comments, it sounds like you've started down an unproductive path.

You might want to refer to a good tutorial on object-oriented design and analysis such as "Head First OOA&D"

I'm on the stage of learning cakephp, which is a OO based framework, but i have not a good understanding of OO. I come from C procedural field.

I need something which can help me think in OO perspective. Can you advicxe me about what can I do/read/watch.... in order to help me think in OO.

Head First: Object Oriented Analysis and Design is a very good book which may be followed by Head First: Design Patterns from the same series.

I want to study some approaches on realizing a project, designing an application, and so on. I'm not referring to Design Patterns as much as i'm referring at some design styles. For example MVC. So, in that order, I need some links, book names or other suggestions to study on this topic. If you have some thoughts, please help me. Thanks.

I would start by reading upon Domain Driven Design. Eric Evans Tackling Complexity in the Heart of Software is a must-read on this topic. I can then recommend reading Jimmy Nilssons Applying Domain Driven Design and Patterns. This book has examples in .NET (C#) but you should be able to apply it to your language of choice.

Code Complete by Steve McConnell is also a good read if you want to learn how to write clean, maintainable code.

If you like Head Firsts books, i can also recommend reading Object-Oriented Analysis & Design.

For the record, MVC is a design pattern.