We commonly use StopWatch from Apache Commons StopWatch check the pattern how they've provided. IllegalStateException is thrown when the stop watch state is wrong. public void stop() Stop the stopwatch. This method ends a new timing session, allowing the time to be retrieved. Throws: IllegalStateException - if the StopWatch is...
ruby,oop,encapsulation,argument-error
I'd say, that the error of number of arguments (1 for 0) is caused by your set_first_name and set_last_name methods, which are declared not to accept any arguments: class EncapsulatedPerson # ... def set_first_name @first_name = name end def set_last_name @last_name = name end end Try updating them, so they...
Simply create a normal class without static methods, ditch the singleton pattern aside, and create an instance. The burden of singleton pattern usually outweigh any benefit....
You dont need to add two function to do same work all you need to do is pass parameter to function public function getResultsByID($userID = null,$flag){ $sqlParams = array(); if (!$userID) { throw new Exception("No User ID Provided"); } $sqlParams['userID'] = $userID; if($flag=value1){ $sql = "SELECT t.user_id,t.owner_id,t.store_id FROM users t...
You are trying to print print witch.enemy_name But the attribute is self.name = enemy_name So you should be calling print witch.name ...
Your classes would be as follows, note that there is no notion of public vs private so you do not need setters and getters class Foo: def __init__(self, fooName): self.fooName = fooName class Bar: def __init__(self, barName, foo): self.barName = barName self.foo = foo As an example >>> f =...
Design patterns are solutions to programming problems that automatically implement good design techniques. Someone has already faced the issues you’re facing, solved them, and is willing to show you what the best techniques are. Answer to your question is - Design patterns are higher level than libraries. Design patterns tell...
javascript,oop,jquery-mobile,mobile
It honestly depends what you want to do with this array If you are going to send it via an XMLHTTPRequest then I'd say you should use JSON format. var arr_of_objs = [{},{}]; //fill it up however you need it If this array is going to consist of objects with...
When you create a class instance, the metaclass's (whose instance the class is) __call__ is called. # Instantiate class. StandardClass() # StandardClass.__call__ is not called! When you create a class instance and then "call" the instance, then the class's __call__ is called. I don't think decorating __call__ with classmethod will...
In db.php class dbConnect { protected $connection; function __construct() { require_once('config.php'); } function Connect() { $this->connection = mysqli_connect(hostname, username, password); if ($this->connection === FALSE) { die('Could not connect to the database because: ' .mysqli_connect_error()); } mysqli_select_db($this->connection, database); return $this->connection; } public function Close() { mysqli_close($this->connect); } } In class.User.php: protected...
You can use get_class() passing it the current object reference, like so: class Base_class { function __construct() { $calledClassName = get_class($this); } } Edit: You can find more info on get_class() in the PHP manual http://php.net/manual/en/function.get-class.php...
Assuming your EntityQuery.groovy ( model )looks like : private String typeName private Order order Assuming you have Order.groovy ( model ) that looks like : private String fieldName; private String orderType; private String orderName; use these model chain as a parameter, I think that is still strongly-typed (correct me). Your...
I would say that in object oriented programming the use of statics should me minimized, but they do have a place. It takes a bit of time to develop a good sense for when static methods/variable are appropriate, so I would start out only using them in a small set...
You could make B's children override a different function: class B : public A { protected: void update_current() override final { do_something_important(); do_something_important_later(); }; virtual void do_something_important_later() = 0; }; With: class C2 : public B { protected: void do_something_important_later() override { do_something_very_important_2(); }; }; ...
java,oop,inheritance,polymorphism,instanceof
Since this is clearly a homework exercise, it is not appropriate for me to provide an answer directly. Instead, I have written a little program for you to demonstrate what the question means, and running it will provide an answer. You can try this out for yourself: public class Main...
The only way to do exactly what you're asking for is to subclass python build-in class list. This should help....
You could do that by implementing the magic method __call(). However, I would strongly recommend against it. Using magic methods is a lot slower, and it's harder for IDEs to display code insight information. Also, you would still wind up with almost as much code, unless you pass everything on...
Answer: None of the above. Try something like this: function Car(loc) { this.loc = loc; } Car.prototype.move = function () { this.loc++; }; var obj = new Car(someLoc); obj.move(); This uses object prototyping which is JavaScript's implementation of object-oriented programming. You can read more about prototypes and inheritance here on...
Generally speaking, since this refers to the current instance, how is it possible that Fireball.onChat(PlayerChatEvent) is registered too? Because when you're constructing an instance of Fireball, this refers to the Fireball being constructed at execution time. The compile-time type of this is Spell, but if you print out this.getClass()...
Your posted sample code has syntax errors. Fix those and the code does what you're wanting. public class Customers { private List<String> names; public Customers(List<String> names) { this.names = names; } public List<String> getNames() { return names; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (String...
java,oop,boolean,encapsulation
A boolean value is a primitive data type and is thus passed by value only. Only objects are passed by reference. So there are two options for you. Either make your primitive boolean value a Boolean object (as this will be passed by reference). Or have the method return a...
on one hand, x and y are arrays of primitive so the array is partial considered as primitive so it may copy the values to a new array, like normal int: You are correct in "arrays of primitive" but not in "partial considered as primitive". Array is an array,...
No, it isn't possible in Java. Because, you can not modify the return type of a function you override. The Java Tutorials Overriding and Hiding Methods says (in part) An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and...
There are a lot of questions on dynamic_cast here on SO. I read only a few and also don't use that method often in my own code, so my answer reflects my opinion on this subject rather than my experience. Watch out. (1.) Why is casting up/down considered bad design,...
Yes, you can use only underscore for the class name. class _{ function __construct(){ echo 'It works!'; } } new _(); Output: It works! DEMO...
With CommonJS (Browserify), what you export will be what you get when you call require (however, be careful with assuming what you export is a singleton, it's not always the case from my experience). So in this case, you want to export the Human class directly. Then in each file...
The basic idea is that you add each instance of a car to the dealership, but note that I changed car_inventory to be an instance member of Dealer. This is because you want each new dealership you make to have its own car_inventory. If you left it as a class...
As @OliverCharlesworth points out, it can't be done directly. You will either have to resort to reflection (though I wouldn't recommend it!) or a series of field-by-field assignments. Another option though, would be to switch from inheritance to composition: public class BetterThing implements IBetterObject { Thing delegate; public BetterThing(Thing t)...
It's somewhat vague what you're asking, but if valueToUseHere is not used outside of doStuff, then don't make it a property! class someClass { public function doStuff() { $valueToUseHere = 60; // Do more stuff here... } } If there's no reason to share that value with other methods of...
Create a variable to store your prepared statement then execute that. $connection = MYSQLDatabase::getInstance()->getConnection(); $statement = $connection->prepare("INSERT INTO users etc etc......."); $insertArray = $statement->execute(array( ":username" => $_POST["username"] )); ...
If I understand you correctly, you're saying that you want an inheritance hierarchy in your interfaces as well as your classes. This is how you'd achieve such a thing: public interface IBase { // Defines members for the base implementations } public interface IDerived : IBase { // Implementors will...
lorem is a method of an anonymous sub-class of B. Therefore you can't call it by using a reference of class B, and since it's anonymous, you can't cast b to a type that contains lorem.
I think the problem is in this line: currentNodePtr->data = &new_car; of the function void StringOfCar::push(Car & new_car). That should be currentNodePtr->data = currentCarPtr; ...
Your source code and documentation contradict each other (although each one might make some sense on its own). The is-a relationship in (runtime) C++ is through inheritance alone (see the Liskov Substitution Principle). In this case, the relationship is has-a, or implemented-in-terms-of. Making the composition through pointers might make sense...
javascript,oop,closures,prototype
Mi question are: what is exactly the difference in using the Box prototype or not? is any approach better for any reason(cost, legibility, standard...)? Functions (and other properties) on the prototype are shared between instances; if you create them in your constructor function, each instance gets its own copy...
Here is an example of a swift program that deals with pets. I found it on here. It has a protocol Animal that defines parts to an animal, with int legs, and boolean domesticated. protocol Animal { var legs: Int { get set } var domesticated: Bool { get }...
java,user-interface,oop,jtextfield,jtextarea
You're almost there. Move the section of code where you clear your JTextFields before the section of code where you check hours worked are within range. Then return just after you show your error message. That way execution of the method does not continue. //Clears JTextFields before checking the error...
By default its an instance of global Object constructor. By default, the last object in each prototype chain is Object.prototype. It's actually not an instance of Object: > Object.prototype instanceof Object false simply because Object.prototype doesn't have a prototype itself. does JavaScript have a reserved instance of Object which...
If you don't mind pulling Node out into an abstract class you can specify the type as part of the generic signature like so: public abstract class AbstractNode<T, U extends AbstractNode<T, U>> { ... public U getLeft() { ... } ... } // inherited getLeft() will return Node<T> public class...
Modify your addError function: public function addError($error, $key=false){ if($key){ self::$_errors[$key] = $error; }else{ self::$_errors[] = $error; } } Then it will go like this: if(strlen($value) < $rule_value){ $this->addError("More than {$rule_value} characters are needed as {$item}.", 'min_notmet'); } If you don't provide $key parameter, it will just add the element as...
php,oop,model-view-controller,controller
No, bootstrap file is for initialization. A controller is resoponsible for handling user input (requests in a web environment) and providing him an output (responses in a web environment). A front controller is just a centralized point for handling incomming requests. None of these compoments should have the responsibility of...
The class B should be as follows: public class B extends A{ public String foo(String s){ return s+s; } public A getA(boolean flag){ if (flag){ A a = new A(); return(a); } else{ B b = new B(); return (b); } } } ...
Use Getters and Setters. The below code will let the $mesh_name property be read, but not written by external code. class MyObject { protected $mesh_name = 'foo'; protected $accessible = ['mesh_name']; protected $writable = []; public function __get($name) { if( in_array($name, $this->accessible) ) [ return $this->name; } else { //...
java,oop,inheritance,coupling,cohesion
No. Naming standards don't do, open or restrict anything. For encapsulation you will of course need access modifiers. Best is to use both. That helps understanding your code even if you didn't look at it for some time or if you indend to share it.
Yes, you want to use gulp or grunt. I suggest gulp, but that's a personal preference. You can use this to inject your scripts in a particular order based on your file naming convention.
You're doing two conflicting things $con= new mysqli('localhost','root','','afiliate'); $query="SELECT * FROM product WHERE ID=? "; $stmt->bind_param("i",$ID); /* $ID has a value, it's ok */ $stmt->execute(); So at this point $stmt is a mysql_stmt object. If you have mysqlnd installed you can do this $result = $stmt->get_result(); while($row=$result->fetch_row()){ echo $row['name']; }...
c#,oop,architecture,software-design,code-design
Place a UserControl on each tab.
php,wordpress,oop,pagination,instagram
I've added the following lines of code to the try block of my try...catch statement to return several successive pages at a time: while ( count( $this->data["photos"] ) < 160 ) { $this-> api_request( $this->data["next_page"] ); } This essentially tells api_request to call itself until my $this->data["next_page"] array is populated...
I would create a list of all your matrices using mget and ls (and some regex expression according to the names of your matrices) and then modify them all at once using lapply and colnames<- and rownames<- replacement functions. Something among these lines l <- mget(ls(patter = "m\\d+.m")) lapply(l, function(x)...
The definition of your BinarySearchTree is: public class BinarySearchTree<Element> extends Tree<Element, Node<Element>> Here, Element is a type-parameter, but not the actual type Element. It's pretty much the same, as you did: public class BinarySearchTree<T> extends Tree<T, Node<T>> Now the error you're getting makes more sense: The type T is not...
I would create a base Asset class and have AssetA and AssetB inherit from it. The factory class should be a separate class - AssetFactory - with just one single responsibility - it should create new Asset object based on some conditions.
You can do this with a self referential parent. Table Business [BusinessID, BusinessLevelID, ParentBusinessID] Table BusinessLevel [BusinessLevelID, Description ]{eg. business, division, dept } ...
You can use at least three ways to do it: property_exists() isset() ReflectionClass::hasProperty() All of these are demonstrated below: <?php class myClass { public $a=1; public $b=2; public $c=3; } $myObj = new myClass(); $reflectionClass = new ReflectionClass($myObj); foreach (['a', 'b', 'c', 'd'] as $property) { printf("Checking if %s exists:...
Instead of building a class to create the booking objects, it would be advisable to either create a standalone function, or a function within a parent class to achieve this. The issue I run in to with using fetchAll() with the FETCH_CLASS parameter, is that the objects do not automatically...
These are Rails methods: You can find valid? here and its code on Github. Likewise with new_record?, you can find a description and its source code here. Also, here is a link to the Rails repository on Github. These methods are not defined in the project, they are defined in...
Maybe can put contactsAppModel.init(); on the first line of your contactsApp.init() method.
This will solve the problem, seasonMap contains values in the order you need (assuming classes implement Comparable) Map<Season, Map<Building, List<Info>>> seasonMap = new TreeMap<>(); for (Building building : buildings) { for (Map.Entry<Season, List<Info>> e : building.infosBySeason.entrySet()) { Season season = e.getKey(); List<Info> infos = e.getValue(); if (!seasonMap.containsKey(season)) { seasonMap.put(season, new...
java,oop,inheritance,integer,literals
Numeric literals are specified in JLS 3.10.1. A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer....
You can pass $_GET in the constructor from your class: Class GetClass { public $action; public function __construct($get){ $this->action = isset($get['action']) ? $get['action'] : null; $this->db = new Db(); $this->Select($this->action); } private function Select($action){ if (strtolower($action) == 'delete') { echo "Here"; } } } $getClass = new GetClass($_GET); ...
You're doing it wrong First thing is that PHP4-style constructors are deprecated, use __construct method to define a costructor. Second is that you must not return from constructor but rather keep the connection object inside class as instance property. Third is that you must call parent methods using parent keyword....
php,class,oop,laravel,laravel-5
That's simple php stuff. Set the attribute as static and access it with ::. class LanguageMiddleware { public static $languages = ['en','es','fr','de','pt','pl','zh','ja']; } @foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang) ... @endforeach You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and...
It depends on whether you have many fields specific to agenda (not to month). If you do, it's better to have one separate model for agenda. BTW, It seems user and agenda are many-to-many relationship. In this case, you need one intermediate model between user and agenda. ...
java,class,oop,methods,casting
When using inheritance within classes, overriding a method will ALWAYS call the child method regardless of casting. You can never change the type of an object, so a RockMusician - although it is an extension of Musician - is still a RockMusician and will be called by its type, not...
Thanks to Sotirios Delimanolis for Help: this is possible with defining the static method and import it statically in every where you want. package factorypakcage; public class firstFactory{ public static factoryFunction(String className){ //switch case for class creation } } Using like this import static factorypakcage.firstFactory.factoryFunction; ... MyClass MyObj = factoryFunction("Class...
Using a trait depends on 2 things : Do you want to use RestController methods for some classes that doesn't depend on Controller ? Since you will surely use some Controller methods to write RestController, I think the answer is no. Do you plan to create others classes that you...
A bigger question is; why is there no class file for int[]? Without such a class file there is no where to put such a method, so it is purely a language feature. It looks like a field of int[] but it not. They could have made it look like...
d4Rk's answer was very close, however you should try not call virtual methods from a constructor as bad things can happen. However if you use a combination of Lazy loading tricks and ISupportInitialize you can defer the creation of the plugin till after the constructor is finished. public abstract class...
$role = userrole::get_premium_subscritpion(1); I notice that you are trying to call a non-static function in a static way You may either change the function to static or change the way you call this function public static function get_premium_subscritpion { or $obj = new userrole(); $role = $obj->get_premium_subscritpion(1); ...
You probably meant: class Keys(): def __init__(self): self.key_list = {1:"one", 2:"two", 3:"three"} def get_name(self, key): self.ddd = key key1 = Keys() key1.get_name(1) Note the use of parenthesis: key1 = Keys()...
In my opinion, the interface should use generics, so you can rely on the implementation of the interface. I would suggest something like this: public interface UserHandler<TRequest, TResponse> where TRequest : CheckUsernameRequest where TResponse : CheckUsernameResponse { } Then FooHandler would become: public class FooHandler : UserHandler<FooRequest, FooResponse> { }...
c++,oop,inheritance,polymorphism
The easiest way is probably to just make method() a virtual member function on foo: class base { public: virtual void method() const = 0; }; class foo : public base { public: void method() const override { } }; int main(){ foo f; base* b = &f; b->method(); }...
python,python-2.7,oop,properties,encapsulation
You need to use self. when accessing member variables: def __init__(self): self.__pro = 1 @property def pro(self): return self.__pro *10 ...
Without really knowing the particulars of your situation, the classic answer is this: if your class initializer requires a whole bunch of arguments, then it is probably doing too much, and it should be factored into several classes. Take a Car class defined as such: class Car: def __init__(self, tire_size,...
A friend function is a non member function which has access to private members of a class. But you still have to provide the object details for accessing data members. The usage of eat function must be similar to object_name.eat() in the feed function....
How about this <?php class MyClass { public $myArray=array(); public $htm = NULL; public function __construct(&$format=NULL) { //.. //Mysql query as $stmt //.. $this->myArray=$stmt->fetchAll(PDO::FETCH_ASSOC); $i=0; foreach($this->myArray as $row) { switch ($format) { case 'Page1' : $this->htm .= $this->format1($row); break; case 'Page2' : $this->htm .= $this->format2($row); break; default: $this->htm .= $this->format_default($row);...
java,oop,object,inheritance,immutability
They are called enumarations. You can find detailed info here they are defined as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } and used as: public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) {...
Your solution is perfectly valid for Java. You are actually using the design pattern Use Composition Over Inheritance. As @Naruto_Biju_Mode says in a comment, if you are using Java 8, you can move the implementation to a default method of Transformable however you would have to make the helper class...
python,function,class,oop,methods
Not sure I got your question right, but you may want to try: def getStats(self): return "width: %s\nheight: %s\narea: %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter()) To satisfy requirements 4 and 6, I would suggest something like: class Shape(object): def area(self): raise NotImplementedError def perimeter(self): raise NotImplementedError class Rectangle(Shape): def...
You can't use type hints with scalar values ( in you case string - check the docs) Change your constructor in this way: public function __construct($scheme, $hostname, $www) { $this->scheme = $scheme; $this->hostname = $hostname; $this->www = $www; } and it should work...
You can use $attr where your question marks are because it is still in scope when you declare the attributes. foreach my $attr (@getDefaultsFromWrappers) { has $attr => ( is => 'rw', default => sub { shift->wrapped->$attr() }, lazy => 1, ); } The following is a possible alternative, which...
There is actually no real difference between both. You can realize an interface with a class as well as with a component. Also you can show the realization in both cases with the socket/lollipop notation. Components are not much different to classes. You can think of a component as a...
java,oop,design,domain-driven-design
For a system-wide password expiration policy your approach is not that bad, as long as your UserPasswordService is a domain service, not an application service. Embedding the password expiration policy within User would be a violation of the SRP IMHO, which is not much better. You could also consider something...
<?php abstract class abc { protected $te; } class test extends abc { public function __construct() { $this->te = 5; } public function team() { $this->te += 100; } public function tee() { return $this->te; } } $obj = new test(); $obj->team(); echo $obj->tee(); -- edit: to make at least...
Varargs (Variable Arguments) Varargs (introduced in Java SE 5) allows you to pass 0, 1, or more params to a method's vararg param. They let you pass any number of objects of a specific type.This reduces the need for overloading methods that do the similar things. For example, public static...
Whenever a method in a struct modifies one of its own properties, you have to use the mutating keyword. I believe that if you write: mutating func intializeAllDataPoints() { ... } it should work for you. This article gives a little more background information....
c++,arrays,oop,multidimensional-array
char *levelchargement[][]= new char [widthmap][heightmap]; is not a valid declaration or allocation for a multi-dimentional array. Since you are dynamically allocating the array at runtime, you need to move the allocation into the class constructor and use this syntax instead: class Map{ public: Map(); Map(const Map&); ~Map(); ... char **levelchargement;...
It is a very good idea to refactor this code; it is an example of DRY. The best way in this case would be to use inheritance: write all common code in the ViewController class, e.g. ViewController.h @interface ViewController : UIViewController { // Variables which are declared here can also...
This is called "dynamic binding" in Java. You can read this on details here, for example http://www.studytonight.com/java/dynamic-method-dispatch.php
Use array_object[i]->get_data(); instead of array_object[i].get_data();. The DOT(.) operator is used when an object try to access its class member functions/variables whereas Arrow(->) operator is used if the object is a pointer. Now, you declared Matrix *array_object[100]; Which means array_object is an array of Matrix pointers. Hence you need to use...
Encapsulation principle is about restricting some parts of an object (e.g. internal operations or fields that shouldn't be available from outside of the object). Common understanding is also using accessors to access fields. Javascript doesn't offer any mechanism that allow restricting access to fields or methods. However, it is possible...
javascript,class,oop,object,methods
Welcome to the world of javascript where you are not using it to just paint and moves boxes :) Coming to your question: //Initialize objects var spaceButton = new Navigation('#spaceWarp'); var stars1 = new Stars('#stars1'); var stars2 = new Stars('#stars2'); var stars3 = new Stars('#stars3'); The initialization of your objects...
It looks alright for a basic implementation, beside that you shouldn't echo something inside a class. If you want see a well implemented solution, have a look into eloquent created by taylor otwell. That should give you heaps of ideas how to improve your code. https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Connection.php...
Because scope in which function2 is defined does not contain definition of object1. Then when you try to access object1.object2 it throws error because object1 is not defined