Search Results

Search found 30246 results on 1210 pages for 'object persistence'.

Page 23/1210 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • What is the use of Association, Aggregation and Composition (Encapsulation) in Classes

    - by SahilMahajanMj
    I have gone through lots of theories about what is encapsulation and the three techniques of implementing it, which are Association, Aggregation and Composition. What i found is, Encapsulation Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code. Association Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently. Aggregation Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship. Composition Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. The question is: Now these all are real world examples. I am looking for some description about how to use these techniques in actual class code. I mean what is the point for using three different techniques for encapsulation, How these techniques could be implemented and How to choose which technique is applicable at time.

    Read the article

  • Validation and Error Generation when using the Data Mapper Pattern

    - by AndyPerlitch
    I am working on saving state of an object to a database using the data mapper pattern, but I am looking for suggestions/guidance on the validation and error message generation step (step 4 below). Here are the general steps as I see them for doing this: (1) The data mapper is used to get current info (assoc array) about the object in db: +=====================================================+ | person_id | name | favorite_color | age | +=====================================================+ | 1 | Andy | Green | 24 | +-----------------------------------------------------+ mapper returns associative array, eg. Person_Mapper::getPersonById($id) : $person_row = array( 'person_id' => 1, 'name' => 'Andy', 'favorite_color' => 'Green', 'age' => '24', ); (2) the Person object constructor takes this array as an argument, populating its fields. class Person { protected $person_id; protected $name; protected $favorite_color; protected $age; function __construct(array $person_row) { $this->person_id = $person_row['person_id']; $this->name = $person_row['name']; $this->favorite_color = $person_row['favorite_color']; $this->age = $person_row['age']; } // getters and setters... public function toArray() { return array( 'person_id' => $this->person_id, 'name' => $this->name, 'favorite_color' => $this->favorite_color, 'age' => $this->age, ); } } (3a) (GET request) Inputs of an HTML form that is used to change info about the person is populated using Person::getters <form> <input type="text" name="name" value="<?=$person->getName()?>" /> <input type="text" name="favorite_color" value="<?=$person->getFavColor()?>" /> <input type="text" name="age" value="<?=$person->getAge()?>" /> </form> (3b) (POST request) Person object is altered with the POST data using Person::setters $person->setName($_POST['name']); $person->setFavColor($_POST['favorite_color']); $person->setAge($_POST['age']); *(4) Validation and error message generation on a per-field basis - Should this take place in the person object or the person mapper object? - Should data be validated BEFORE being placed into fields of the person object? (5) Data mapper saves the person object (updates row in the database): $person_mapper->savePerson($person); // the savePerson method uses $person->toArray() // to get data in a more digestible format for the // db gateway used by person_mapper Any guidance, suggestions, criticism, or name-calling would be greatly appreciated.

    Read the article

  • Object Oriented Design Questions

    - by Robert
    Hello there. I am going to develop a Tic-Tac-Toe game using Java(or maybe other OO Languages).Now I have a picture in my mind about the general design. Interface: Player ,then I will be able to implement a couple of Player classes,based on how I want the opponent to be,for example,random player,intelligent player. Classes: Board class,with a two-dimensional array of integers,0 indicates open,1 indicates me,-1 indicates opponent.The evaluation function will be in here as well,to return the next best move based on the current board arrangement and whose turn it is. Refree class,which will create instance of the Board and two player instances,then get the game begin. This is a rough idea of my OO design,could anybody give me any critiques please,I find this is really beneficial,thank you very much.

    Read the article

  • Object.Watch with disabled attribute

    - by Benjamin Fleming
    <html> <head> <script type="text/javascript"> window.onload = function() { var btn = document.getElementById("button"); var tog = document.getElementById("toggle"); tog.onclick = function() { if(btn.disabled) { btn.disabled = false; } else { btn.disabled = true; } }; //btn.watch("disabled", function(prop, val, newval) { }); }; </script> </head> <body> <input type="button" value="Button" id="button" /> <input type="button" value="Toggle" id="toggle" /> </body> </html> If you test this code, the Toggle button will successfully enable and disable the other button. However, un-commenting the btn.watch() line will somehow always set the disabled tag to true. Any ideas?

    Read the article

  • Class Design - Returning a List<Object> From <Object>

    - by Mike
    Given a simple class: public class Person { public string FirstName; public string LastName; public string GetFullName() { return FirstName + LastName; } } The user of this class will populate a List<Person> object by reading an Xml file or some other data source. Should the logic for populating the List be in the Person class or should it just remain in the calling class? In other words, should there be a public List<Persons> GetPersons() method in the Person class or in the calling class? Or should the data accessor be in another class altogether? I know this is a rather simplistic question but I'm just curious how others typically do it.

    Read the article

  • WPF ComboBox Object Binding - not updating DataContext Object

    - by Jaysen
    Hello, I have the following scenario: 1 class called 'Widget' with the properties: ID, Code, Description 1 class called 'MyWidget' with a property: m_Widget As Widget 1 ComboBox The ComboBox has a List(Of Widget) set as the ItemSource. I create an instance of 'MyWidget' named MyWidget1 and I set the property values of the m_Widget to match one of the items in the 'ComboBox List(Of Widget)'. I then set the DataContext of the ComboBox to MyWidget1.Widget. When I change the ComboBox selected item, only the ID property of 'MyWidget1.Widget' gets updated... How do I get the object 'Widget' on 'MyWidget1' to be updated instead of just 'MyWidget1.Widget.ID'? Here is a link to a sample project demonstrating this scenario: http://www.webpersona.com/ObjectBinding.zip Thanks in advance for any help :)

    Read the article

  • How to determine whether a dependency object implements a given dependency property (C# / WPF)

    - by Tim Coulter
    I am working with the classes in the System.Windows.Documents namespace, trying to write some generic code that will conditionally set the value of certain dependency properties, depending on whether these properties exist on a given class. For example, the following method assigns an arbitrary value to the Padding property of the passed FrameworkContentElement: void SetElementPadding(FrameworkContentElement element) { element.SetValue(Block.PaddingProperty, new Thickness(155d)); } However, not all concrete implementations of FrameworkContentElement have a Padding property (Paragraph does but Span does not) so I would expect the property assignment to succeed for types that implement this property and to be silently ignored for types that do not. But it seems that the above property assignment succeeds for instances of all derivatives of FrameworkContentElement, regardless of whether they implement the Padding property. I make this assumption because I have always been able to read back the assigned value. I assume there is some flaw in the way I am assigning property values. What should I do to ensure that a given dependency property assignment is ignored by classes that do not implement that property? Many thanks for your advice. Tim

    Read the article

  • Object declaration in Objective-C

    - by Sahat
    Is there any difference in declaring objects in Objective-C between (1) and (2), besides the style and personal preference? (1) One-line declaration, allocation, initialization. Student *myStudent = [[Student alloc] init]; (2) Multi-line declaration, allocation, initialization. Student *myStudent; myStudent = [Student alloc]; myStudent = [myStudent init];

    Read the article

  • find(:all) and then add data from another table to the object

    - by Koning Baard XIV
    I have two tables: create_table "friendships", :force => true do |t| t.integer "user1_id" t.integer "user2_id" t.boolean "hasaccepted" t.datetime "created_at" t.datetime "updated_at" end and create_table "users", :force => true do |t| t.string "email" t.string "password" t.string "phone" t.boolean "gender" t.datetime "created_at" t.datetime "updated_at" t.string "firstname" t.string "lastname" t.date "birthday" end I need to show the user a list of Friendrequests, so I use this method in my controller: def getfriendrequests respond_to do |format| case params[:id] when "to_me" @friendrequests = Friendship.find(:all, :conditions => { :user2_id => session[:user], :hasaccepted => false }) when "from_me" @friendrequests = Friendship.find(:all, :conditions => { :user1_id => session[:user], :hasaccepted => false }) end format.xml { render :xml => @friendrequests } format.json { render :json => @friendrequests } end end I do nearly everything using AJAX, so to fetch the First and Last name of the user with UID user2_id (the to_me param comes later, don't worry right now), I need a for loop which make multiple AJAX calls. This sucks and costs much bandwidth. So I'd rather like that getfriendrequests also returns the First and Last name of the corresponding users, so, e.g. the JSON response would not be: [ { "friendship": { "created_at": "2010-02-19T13:51:31Z", "user1_id": 2, "updated_at": "2010-02-19T13:51:31Z", "hasaccepted": false, "id": 11, "user2_id": 3 } }, { "friendship": { "created_at": "2010-02-19T16:31:23Z", "user1_id": 2, "updated_at": "2010-02-19T16:31:23Z", "hasaccepted": false, "id": 12, "user2_id": 4 } } ] but rather: [ { "friendship": { "created_at": "2010-02-19T13:51:31Z", "user1_id": 2, "updated_at": "2010-02-19T13:51:31Z", "hasaccepted": false, "id": 11, "user2_id": 3, "firstname": "Jon", "lastname": "Skeet" } }, { "friendship": { "created_at": "2010-02-19T16:31:23Z", "user1_id": 2, "updated_at": "2010-02-19T16:31:23Z", "hasaccepted": false, "id": 12, "user2_id": 4, "firstname": "Mark", "lastname": "Gravell" } } ] I thought of a for loop in the getfriendrequests method, but I don't know how to implement this, and maybe there is an easier way. It must also work for XML. Can anyone help me? Thanks

    Read the article

  • copying the request header from request object to urlConnection object

    - by Bunny Rabbit
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub URL url = new URL("http://localhost:8080/testy/Out"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); PrintWriter out=response.getWriter(); for(Enumeration e=request.getHeaderNames();e.hasMoreElements();){ Object o=e.nextElement(); String value=request.getHeader(o.toString()); out.println(o+"--is--"+value+"<br>"); connection.setRequestProperty((String) o, value); } connection.connect(); } i wrote the above code in a servlet to post form so some alternate locations than this servlet,but its not working.is it okay to use connection.setRequestProperty to set the header fields to what they are in the incoming request to servlet.

    Read the article

  • wpf c# databinding on object

    - by Enriquev
    Hello, say I have this control: public partial class bloc999 : UserControl { bloc999Data mainBlock = new bloc999Data(); public bloc999() { InitializeComponent(); mainBlock.txtContents = "100"; base.DataContext = mainBlock; } } in the xaml: <TextBox Margin="74,116,106,0" Name="txtContents" Text="{Binding Path=txtContents, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" /> <TextBox Margin="74,145,106,132" Name="txtContents2" Text="{Binding Path=txtContents2, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" /> Then I have this class: public class bloc999Data : INotifyPropertyChanged { string _txtContents; string _txtContents2; public event PropertyChangedEventHandler PropertyChanged; void NotifyPropertyChanged(string propName) { if (this.PropertyChanged != null) this.PropertyChanged( this, new PropertyChangedEventArgs(propName)); } public string txtContents2 { get { return this._txtContents2; } set { if (int.Parse(value) > int.Parse(this._txtContents)) { this._txtContents2 = "000"; } else this._txtContents2 = value; NotifyPropertyChanged("txtContents2"); } } public string txtContents { get { return this._txtContents; } set { this._txtContents = value; NotifyPropertyChanged("txtContents"); } } } Ok now say I have A button on the form and I do this in the code: mainBlock.txtContents2 = "7777777"; It puts 000 in the textbox, but If i just type in manually, in the textbox (txtContents2, the setter code is called but for some reason the textboxes value does not change, the instance value does change. help?

    Read the article

  • how does object programming work?

    - by venom
    Hello, I am not sure about some things in oop. If I have Class1, which has some private field, for example private Field field1, and make getField1(){return field1;} then I have some class with constructor public Class2(Field field){someMethod(field);} And then I call constructor of Class2 in Class3 like: Class2 cl = new Class2(instanceOfClass1.getField1()); And now the question: Am I working with field1 of instanceOfClass1 in "someMethod(field)"?

    Read the article

  • Returning new object, overwrite the existing one in Java

    - by lupin
    Note: This is an assignment. Hi, Ok I have this method that will create a supposedly union of 2 sets. i mport java.io.*; class Set { public int numberOfElements; public String[] setElements; public int maxNumberOfElements; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { this.numberOfElements = numberOfE; this.setElements = new String[setE]; this.maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { if (setElements[i] != null) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newYtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newXtemparray.length; j++) { temp.add(newXtemparray[j]); } return temp; } Set difference(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newXtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newYtemparray.length; j++) { int retval = temp.findElement(newYtemparray[j]); if( retval != -1 ) { temp.remove(newYtemparray[j]); } } return temp; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(0,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element sixb is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); //setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); //setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); //setA.printSet(); Set setB = new Set(0,10,10); setB.add("b"); setB.add("z"); setB.add("x"); setB.add("y"); Set setC = setA.union(setB,setA); System.out.println("Elements of setA"); setA.printSet(); System.out.println("Union of setA and setB"); setC.printSet(); } } The union method works a sense that somehow I can call another method on it but it doesn't do the job, i supposedly would create and union of all elements of setA and setB but it only return element of setB. Sample output follows: java SetDemo Enter string element to be added hello You entered hello Set size is: 10 Set is empty? false Element sixb is member of setA? -1 Set is full? true Element b located on index: 2 Set size is: 9 Elements of setA Member elements on index: 0 hello Member elements on index: 1 world Member elements on index: 2 six Member elements on index: 3 seven Union of setA and setB Member elements on index: 0 b Member elements on index: 1 z Member elements on index: 2 x Member elements on index: 3 y thanks, lupin

    Read the article

  • property not updating in object when page is posted

    - by Jared
    Hi I have set a property in a constructor like so function __construct() { $this->count = count(@$_SESSION['filearray']); //count how many files in array } and using it in condition statements if($this->count > 10) //then do something but it appears the count isn't being updated when I use another method of injecting values into this 'filearray' until I refresh the page. am I doing something wrong? I thought that my constructor would detect a change had been made in the session and whenever I call $this-count I would get the current count value but it seems to be 1 step behind until I refresh the page. If this is all vague I can include my form page that has all the method calls, but this is the jist of my question, why is my property not updating and how do I fix it :) TIA

    Read the article

  • getting an error on jslint while creating a new object using javascript

    - by user3712689
    For some reason this code is giving a lint. I can't really figure out why. It says: 'was expecting a assignment or function call, and instead saw an expression.' What does that mean? window.onload = function (){ function SuspectOne (naam, leeftijd, wie){ this.naam = Spencer Hawes; this.leeftijd = 22; this.wie = zoon van de man; } function SuspectTwo (naam, leeftijd, wie){ this.naam = Tyrone Biggums; this.leeftijd = 28; this.wie = lokale herionejunk; } function SuspectThree (naam, leeftijd, wie){ this.naam = Ellie Campbell Hawes; this.leeftijd = 40; this.wie = vrouw van de man; } var verdachten = new Array[]; verdachten[0] = new Verdachte("Spencer Hawes", 22, "zoon van de man"); verdachten[1] = new Verdachte("Tyrone Biggums", 28, "lokale herionejunk"); verdachten[2] = new Verdachte("Ellie Spencer Hawes", 40, "vrouw van de man"); for(x=0; x<verdachten.length; x++){ console.log("De verdachte is de " + verdachten[x].leeftijd + "jaar oud " + verdachten[x].naam + ", de " + verdachten[x].wie); } }; Can someone help me with this? I would really like a lint free code.

    Read the article

  • javascript. is it posible for one member of an object to access another member of that object withou

    - by joox
    For example: var myObj={ myValue="hola", asMember=function(){ alert( this.myValue ); } }; myObj.asMember(); // will work fine var asGlobal=myObj.asMember; // global alias for that member function asGlobal(); // won't work in javascript (will work in AS3, but i need js now) So the question is, can I rewrite asMember so that it could be called by global alias and without mentioning myObj at all? It's understood that if I define it: asMember=function(){ alert( myObj.myValue ); } it will work, but in my case, mentioning myObj is not acceptable even inside the function itself (because myObj may be reassigned later, but asGlobal won't change and should keep working)

    Read the article

  • Where should I put contextual data related to an Object that is not really a property of the object?

    - by RenderIn
    I have a Car class. It has three properties: id, color and model. In a particular query I want to return all the cars and their properties, and I also want to return a true/false field called "searcherKnowsOwner" which is a field I calculate in my database query based on whether or not the individual conducting the search knows the owner. I have a database function that takes the ID of the searcher and the ID of the car and returns a boolean. My car class looks like this (pseudocode): class Car{ int id; Color color; Model model; } I have a screen where I want to display all the cars, but I also want to display a flag next to each car if the person viewing the page knows the owner of that car. Should I add a field to the Car class, a boolean searcherKnowsOwner? It's not a property of the car, but is actually a property of the user conducting the search. But this seems like the most efficient place to put this information.

    Read the article

  • Insert data in an object to a database.

    - by paul
    I am facing the following design/implementation dilemma. I have a class Customer which is below with getters and setters. I would like to insert the value of the Customer into a "Customer" table of a database. But Customer has an address which is of type "Address". How do I go about inserting this field into the database?(I am using sqlite3). I thought of writing a separate table "Address(customerId,doorNo,city,state,country,pinCode)". But I am having second thoughts about generating the primary key(customerId) which should be same for both the "customer" and "Address" table. Sqlite3 faq states that I can do "Integer Primary Key" to use the field to generate an auto number. But if I do that in customer table, I would have to retrieve the same Id to be used in Address table. This kinda looks wrong to me :-?. There should be an elegant method to solve this. Any ideas would be much appreciated. Thanks in advance. import java.io.*; import java.sql.*; class Customer { private String id; private String name; private Address address; private Connection connection; private ResultSet resultSet; private PreparedStatement preparedStatement; public void insertToDatabase(){ } } class Address{ private String doorNumber; private String streetName; private String cityName; private String districtName; private String stateName; private String countryName; private long pinCode; }

    Read the article

  • How do I call functions of an object inside the same object?

    - by Roly
    I have the following Javascript code add_num = { f: function(html, num) { alert(this.page); }, page : function() { return parseInt(this.gup('page')); }, gup : function(name) { name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]'); var regex = new RegExp('[\\?&]'+name+'=([^&#]*)'); var results = regex.exec(window.location.href); if(results == null) return ''; else return results[1]; } } But when I call add_num.f() what I get from alert() is the actual code of page. That is, it returns function() { return parseInt(this.gup('page')); } I was expecting a numeric value and not any code at all.

    Read the article

  • Accessing variables of an object of a particular class through a different class within the construc

    - by Haxed
    class Student { private String name; public Student(String name){ this.name = name; } public String getName(){ return name; } } class StudentServer { public StudentServer(){ Student[] s = new Student[30]; s[0] = new Student("Nick"); System.out.println(s[0]); // LINE 01:But this compiles, although prints junk System.out.println(s[0].getName()); // LINE 02:I get a error called cannot find symbol } public static void main(){ new StudentServer(); } } Hey, there are two lines, I want the reader to focus on, the first line prints junk as usual, but suprizingly the second one gives me an error. Do you know why ? Many Thanks

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >