Computer Science – Game DesignUC Santa Cruz CMPS 20: Game Design Experience Code Organization UML Patterns Code Smells Feb 7 2011 Arnav Jhala.

Slides:



Advertisements
Similar presentations
OOP - Object Oriented Programming Object Oriented Programming is an approach to programming that was developed to make large programs easier to manage.
Advertisements

Bad code smells Refactoring Example Game Design Experience Professor Jim Whitehead January 26, 2009 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Inheritance Inheritance Reserved word protected Reserved word super
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Software Construction and Evolution - CSSE 375 Bad Smells in Code Shawn Bohner & Steve Chenoweth.
Decorator & Chain of Responsibility Patterns Game Design Experience Professor Jim Whitehead February 2, 2009 Creative Commons Attribution 3.0 (Except for.
Computer Science – Game DesignUC Santa Cruz Announcements Website – Readings and sample code updated – Last year’s mid-term exam with answer key – Mid-term.
Computer Science – Game DesignUC Santa Cruz Today Publish/Subscribe Design Pattern Delegates Sprite movement Particles.
Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page: Lecture.
Object-Oriented PHP (1)
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 10 Object-Oriented Modeling.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Procedural vs Object Oriented Design Bad code smells Game Design Experience Professor Jim Whitehead January 23, 2009 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Delegates & Events Observer and Strategy Patterns Game Design Experience Professor Jim Whitehead January 30, 2009 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Exam Questions Chain of Responsibility & Singleton Patterns Game Design Experience Professor Jim Whitehead February 4, 2009 Creative Commons Attribution.
Chapter 10 Classes Continued
Prototype Creational Design Pattern By Brian Cavanaugh September 22, 2003 Software, Design and Documentation.
Modelling classes Drawing a Class Diagram. Class diagram First pick the classes –Choose relevant nouns, which have attributes and operations. Find the.
C++ fundamentals.
OBJECT ORIENTED PROGRAMMING IN C++ LECTURE
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 PRACTICAL OBJECT-ORIENTED DESIGN WITH UML 2e Chapter 2: Modelling.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 12 Object-Oriented.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
School of Computer Science & Information Technology G6DICP - Lecture 22 The Theory of Object Oriented Programming.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Refactoring Improving the structure of existing code Refactoring1.
Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design Guidelines.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object Oriented Software Development
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Incremental Design Why incremental design? Goal of incremental design Tools for incremental design  UML diagrams  Design principles  Design patterns.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CSCI-383 Object-Oriented Programming & Design Lecture 10.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Object-Oriented Design.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 COS 260 DAY 12 Tony Gauvin. 2 Agenda Questions? 5 th Mini quiz –Chapter 5 40 min Assignment 3 Due Assignment 4 will be posted later (next week) –If.
ITEC0724 Modern Related Technology on Mobile Devices Lecture Notes #2 1.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
Testing in OO Environment The reasons for testing is not any different for any of the design and implementation methodologies, including OO methodology.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSCE 240 – Intro to Software Engineering Lecture 3.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 6.0.
Coupling and Cohesion Pfleeger, S., Software Engineering Theory and Practice. Prentice Hall, 2001.
Chapter 11 Object-Oriented Design
Behavioral Design Patterns
Week 4 Object-Oriented Programming (1): Inheritance
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
MSIS 670 Object-Oriented Software Engineering
Advanced Programming Behnam Hatami Fall 2017.
Presentation transcript:

Computer Science – Game DesignUC Santa Cruz CMPS 20: Game Design Experience Code Organization UML Patterns Code Smells Feb Arnav Jhala

Computer Science – Game DesignUC Santa Cruz Unified Modeling Language (UML) A family of diagram types used to model object-oriented software projects – A standard way to graphically represent complex assemblages of objects, components, etc. Two useful diagram types – Class diagram Static view of software Object-oriented classes Relationships – Inheritance – Containment – Sequence diagram Dynamic view Methods calling methods, and in what order Jmgold, Flickr

Computer Science – Game DesignUC Santa Cruz Modeling a Class in UML An object oriented class contains: – Data: class variables Type & visibility of each variable – Methods Name, parameters, types of parameters UML classes can represent all of this myClass varname: type [= init value] … Amethod(type param) Bmethod(type param, …) Class name Class variables (attributes) Class methods and parameters

Computer Science – Game DesignUC Santa Cruz Modeling Visibility The visibility of a variable or method can be indicated using: + public # protected - private Book - title: string + Title > # num_pages: int = 0 + NumPages > … + lookupISBN()

Computer Science – Game DesignUC Santa Cruz Inheritance, Containment Two main relationships modeled in class diagrams – Inheritance (is-a, specialization) – Containment (has-a) shape circlesquare scene + elems: List square and circle are subclasses of (inherit from) shape Class scene contains a set of shapes (via the elems List) Open full triangle arrowhead significant for inheritance (a different arrowhead would not mean the same thing!)

Computer Science – Game DesignUC Santa Cruz Problem: Adding exhaust, shield to spaceship Vertically scrolling 2D space shooters have a spaceship that: – Banks left or right, depending on motion – Typically have three animations: Banking left, straight ahead, banking right Also want to – Add particle effect for exhaust if the ship is moving up the screen But turn this off if it’s moving down the screen – Add a shield in front of the ship if the player picks up a shield powerup Could accomplish all of these visuals using a series of combined animations – Bank left, bank left and shield, bank left and exhaust, bank left and shield and exhaust, etc.. – But, leads to combinatoric expansion Isn’t there a better way? Why, yes! Ikaruga, Treasure

Computer Science – Game DesignUC Santa Cruz Decorating the spaceship with shield & exhaust Instead of pre-defining all possible animations… Draw the shield, exhaust, and spaceship separately – Can think of “decorating” the spaceship with a shield, or an exhaust particle effect, as needed – No longer need large combinations of animations Some powerup options in Gradius Gratuitous picture of a Vic Viper model

Computer Science – Game DesignUC Santa Cruz Decorators using object-oriented code Basic idea is to create a linked list of objects – Each object draws one part of final scene… E.g., the exhaust, the shield, etc. – … then calls the next object on the list – The final object is the main object being decorated E.g., the spaceship spaceship shield exhaust Exhaust, shield, and spaceship are object instances

Computer Science – Game DesignUC Santa Cruz Decorator pattern IComponent interface gives just the decoration Operation() – Can mix in this Interface with a wide range of classes Component is terminal element (spaceship) Decorator provides decorating elements (shield, exhaust) – Diamond-headed arrow indicates that Decorator instances have a reference to an instance of IComponent (another Decorator, or a Component) Example of Decorator pattern

Computer Science – Game DesignUC Santa Cruz Essence of the Decorator pattern The essence of the Decorator pattern – Linked list of object instances, first one calls next one, etc. – Each object adds its particular computation (often, but not exclusively, visual) to the output before passing to next object – It is possible to have multiple chains, each ending at the same terminal (or decorator) object Can pre-arrange commonly used decorator chains

Computer Science – Game DesignUC Santa Cruz Implementation details Need to know next object in chain – Typically passed into the constructor Could have a separate method instead (would need to add this to IComponent May need to know details about terminal object – Need to know position of spaceship to put shield directly in front, and exhaust directly in back – Each object in list can be given reference to terminal object Use reference to spaceship object to retrieve its current location May need to remove a decorator – E.g., shields no longer active – Will need to write code that removes a decorator instance, and repairs the links among remaining ones – If the removed decorator is the first in the chain, removal is easy

Computer Science – Game DesignUC Santa Cruz Decorator Pattern: Pros and Cons Pro: Favors composition over inheritance – Decorator chains created at runtime, can be dynamically changed – Avoids combinatoric expansion of subclasses Pro: Avoids feature-rich parent classes – New decorations are “pay as you go” – Avoids need for adding all features into large, customizable parent class Con: Decorator and component aren’t identical – Requires more complex handling of situations where you really want direct access to terminal component Con: Many little objects – Can result in designs that have lots of little objects that are very similar – Can be hard to learn and debug, since so many classes affect output

Computer Science – Game DesignUC Santa Cruz Problem: Magic system with variable effects Consider a game that has castles, fighters, wizards, and magic cars – Fighters can be inside castles – Wizards have spells: Some only affect the castle, weakening its walls (lightening bolt) Other, more powerful spells, weaken the walls and do damage to the people inside (fireball explosion) If the people inside the castle are inside a magic car, the car absorbs some, but not all, of the damage Need some way to have the applied damage vary depending on who is inside what – E.g., damage depends on containment

Computer Science – Game DesignUC Santa Cruz An approach: Chain of Spell Handlers Create objects that – Represent a cast spell – Represent castles, fighters, cars Create a chain of object references that represent containment – Castle –references-> Car –references-> Fighter Pass each spell object along the containment chain – Castle handles spell first, absorbs some damage, reduces power of spell, and passes it along to Car – Car handles spell, reduces power of spell (no damage – it’s magic), and passes along to Fighter – Fighter handles spell last, applying damage

Computer Science – Game DesignUC Santa Cruz Chain of Spell Handlers Chain of object references looks like Decorator chain – Containment of castle(cars(fighters)) Separate object represents request (spell) fighter car castle fireball power = 100 HP = 500 HP = 100 HP = 50 Fireball spell handed to castle for processing first

Computer Science – Game DesignUC Santa Cruz Chain of Spell Handlers Chain of object references looks like Decorator chain – Containment of castle(cars(fighters)) Separate object represents request (spell) fighter car castle fireball power = 25 HP = 425 HP = 100 HP = 50 Fireball spell handed to castle for processing first Castle reduces its HP, and reduces power of fireball

Computer Science – Game DesignUC Santa Cruz Chain of Spell Handlers Chain of object references looks like Decorator chain – Containment of castle(cars(fighters)) Separate object represents request (spell) fighter car castle fireball power = 10 HP = 425 HP = 100 HP = 50 Castle hands Fireball spell off to car (next in chain), which reduces spell power

Computer Science – Game DesignUC Santa Cruz Chain of Spell Handlers Chain of object references looks like Decorator chain – Containment of castle(cars(fighters)) Separate object represents request (spell) fighter car castle fireball power = 0 HP = 425 HP = 100 HP = 40 Car hands Fireball spell off to fighter (next in chain), which applies remaining spell power as damage. Fighter is end of chain, so no further handoffs.

Computer Science – Game DesignUC Santa Cruz Chain of Responsibility Pattern IHandler interface – Successor: reference to next object in the chain – Request(): method that receives request object (e.g. spell), and takes action on it Handler1, Handler2 – Specific handler implementations (e.g., castle, car, fighter) – Each handles requests in a different way

Computer Science – Game DesignUC Santa Cruz Implementation details Request is often represented as an object instance – In this case, need to add IRequest interface and Request1…RequestN implementations to UML diagram +Request(IRequest r) Request1Request2 // Request state > IRequest

Computer Science – Game DesignUC Santa Cruz Chain of Responsibility: Pros and Cons Benefits – Reduces coupling between requests, and objects that handle requests Would be very easy to add a new character class (say, a thief) and have it handle spells in a class-specific way, without modifying the spell class – Dynamic modification of request handling Can change the chain of request handlers at runtime For example, as fighters enter/exit cars, castles, etc. Drawback – Handling isn’t guaranteed Since it is up to each object in the chain whether to take action, there is no global guarantee that anyone will handle a request

Computer Science – Game DesignUC Santa Cruz Problem: Representing Game State In most computer games, there is some state associated with the entire game – Current level number – Pointer to level data – Time elapsed while playing – High score during this play session Want one and only one instance of the object holding this state Also want to easily gain access to this state anywhere in the game – Avoid need for long data passing chains

Computer Science – Game DesignUC Santa Cruz Approach: Singleton Pattern Singleton pattern ensures only one instance is ever made of a class – Wait.. How is this possible? Can’t I have my code just call “new” as many times as I want? – Not if the constructor is private! Ensures that only code within the class can call the constructor – OK, so now I can’t call new, which means there is no way to ever create an instance, right? – Wrong – a private class variable (“instance”) in the Singleton is initialized by calling the Singleton’s constructor – Great, but how do I get access to “instance” if it’s private? – Use a public static property (“UniqueInstance”). You can always call this since it’s static.

Computer Science – Game DesignUC Santa Cruz Singleton Implementation Constructor is private by default In C#, the first call on any methods, properties or constructors of a class causes its class variables to be set up. – First access to the UniqueInstance property causes variable “instance” to be initialized by calling constructor – Hence, first access to UniqueInstance causes new instance to be created, then returns a reference to it – Clever! Sealed keyword means no subclasses are possible public sealed class Singleton { // Private Constructor Singleton() { } // Private object initialized by calling private // constructor static readonly Singleton instance = new Singleton(); // Public static property is used to retrieve // reference to the Singleton instance public static Singleton UniqueInstance { get { return instance; } } Code from C# 3.0 Design Patterns, p Originally from:

Computer Science – Game DesignUC Santa Cruz Singleton Advantages Pro: – Ensures only one instance of class is ever created – Can get access to data in this class from anywhere Con: – Acts like global variables – Can cause methods to have unintended side- effects, due to data sharing via state in the singleton

Computer Science – Game DesignUC Santa Cruz Readings

Computer Science – Game DesignUC Santa Cruz Writing Good Code Once code has an object-oriented design, can then focus on improving its design – If the design is procedural, can’t even begin to do this Refactoring literature has notion of “code smells” – “If it stinks, change it” (M. Fowler, Refactoring) – A characteristic of a design that is a strong indicator it has poor structure, and should be refactored – Good programming practices It’s not always straightforward that a bad code smell must lead to a refactoring. Have to use judgement. Still, as new designers, bad code smells likely mean you should change your code.

Computer Science – Game DesignUC Santa Cruz Code Smells: Duplicated Code Duplicated code (code clones) – The same, or very similar code, appears in many places – Problem A bug fix in one code clone may not be propagated to all Makes code larger that it needs to be – Fix: extract method refactoring Create new method that encapsulates duplicated code Replace code clones with method call

Computer Science – Game DesignUC Santa Cruz Code smells: Long Method Long method – A method that has too many lines of code How long is too long? Depends. Over 20 is usually a bad sign. Under 10 lines is typically good. Still, no hard and fast rules. – Problem The longer a method, the harder it is to understand, change, and reuse – Example from homework Shooting logic, Main – Fix: extract method Take chunks of code from inside long method, and make a new method Call new method inside the now-not-so-long method.

Computer Science – Game DesignUC Santa Cruz Code smells: Feature Envy Feature Envy – A method in one class uses primarily data and methods from another class to perform its work Seems “envious” of the capabilities of the other class – Problem: Indicates abstraction fault. Ideally want data, and actions on that data, to live in the same class. Feature Envy indicates the method was incorrectly placed in the wrong class – Fix: Move method – Move the method with feature envy to the class containing the most frequently used methods and data items

Computer Science – Game DesignUC Santa Cruz Code smells: Large class Large class – A class is trying to do too much – Many instance variables – Many methods Problem: – Indicates abstraction fault There is likely more than one concern embedded in the code Or, some methods belong on other classes – Associated with duplicated code Fix: – Extract class refactoring Take a subset of the instance variables and methods and create a new class with them This makes the initial (long) class shorter – Move method refactoring Move one or more methods to other classes Example from homework: – Class containing Main() tends to have too much game logic

Computer Science – Game DesignUC Santa Cruz Code smells: switch statements Switch statements – The cases in a switch statement contain logic for different types of instances of the same class – In object-oriented code, this indicates new subclasses should be created Problem – The same switch/case structure appears in many places Fix – Create new subclasses – Extract method to move case block logic into methods on the new subclasses

Computer Science – Game DesignUC Santa Cruz Code smells: Data class Data class – A class that has only class variables, getter/setter methods/properties, and nothing else – Is just acting as a data holder Problem – Typically, other classes have methods with feature envy – That is, there are usually other methods that primarily manipulate data in the data class – Indicates these methods should really be on the data class – Can indicate the design is really procedural Fix – Examine methods that use data in the data class, and use move method refactoring to shift methods

Computer Science – Game DesignUC Santa Cruz Readings Fowler’s book chapters Refactoring Code Smells Linked from website