Menu
  • HOME
  • TAGS

Understanding difference in Swift properties for structs and classes in assignment

ios,swift,oop,struct

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....

Javascript, Array of Objects?

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...

What is the default value of internal [[prototype]] property in JavaScript?

javascript,oop

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...

Validation within Get/Set Methods Java

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...

Why does Instagram's pagination return the same page over and over?

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...

Object Oriented Python - rectangle using classes and functions

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...

Actual class of object reference

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...

Why has java kept length field in the jvm public

java,oop

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...

Getting ArgumenError while trying to create instance of a ruby class

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...

mysqli_query() expects parameter 1 to be mysqli, i cant use a variable?

php,oop,mysqli

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...

Using $_GET in class

php,class,oop

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); ...

Function pointer to singleton class instance function

c++,oop,pointers,singleton

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....

Add key and value (as argument via function) to array

php,oop,associative-array

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...

TypeScript project organization, compile into a single JS file?

javascript,oop,typescript

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.

JS: Is it possible “something(arg)” and “something.my_method(arg)” at same time

javascript,function,oop,methods

Well, this is javacript, and there are many ways to do it. edit: I actually thought about this, and tried to imagine other way to do the same thing, and actually I cannot find any. There's @elcodedocle which I thought about but is close but not what you ask, or...

How Do I Architect Out This Relationship

sql,oop

You can do this with a self referential parent. Table Business [BusinessID, BusinessLevelID, ParentBusinessID] Table BusinessLevel [BusinessLevelID, Description ]{eg. business, division, dept } ...

calling a method to restart if a condition is met without using a loop

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...

Call to a member function query() on a non-object in PHP when trying to access parent constructor in php

php,mysql,oop

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....

Making list of objects of class with function overloading

c++,oop

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; ...

Am I violating the Object-Oriented encapsulation principle? [closed]

javascript,oop

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...

Interface for Child Class that Inherits from parent class without reimplementing parent class

c#,oop,inheritance,interface

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...

Is bootstrap file a controller?

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...

creating multiple objects with browserify

javascript,oop,browserify

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...

JavaScript Functional Classes [closed]

javascript,oop

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...

Global function or function with no name java for factory pattern

java,oop,factory-pattern

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...

Downcasting doesn't work and functions called from object own class instead of where the function is (Java)

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...

Symfony : is it better to use a trait or an intermediary class to complete Controller one?

php,oop,symfony2

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...

Java Design Issue: Enforce method call sequence

java,oop,design-patterns

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...

Is it bad practice to have a static class that does not instantiate objects

java,class,oop

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...

How to check if objectB used instance of objectA from objectA using private variables

php,oop

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 { //...

Python: I'm getting an error when using self.name

python,oop,self

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 ...

Python method that can be called on a list of objects

python,oop,syntax

The only way to do exactly what you're asking for is to subclass python build-in class list. This should help....

missing 1 required positional argument: 'key'

python,oop,python-3.x

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()...

Passing variable data between classes OO Javascript

javascript,oop

Maybe can put contactsAppModel.init(); on the first line of your contactsApp.init() method.

(Java) What kind of argument is this? With a [duplicate]

java,oop

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...

PDO FETCH_CLASS multiple rows into array of objects

php,arrays,oop,pdo

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...

Calling Protected Function From Derived Friend Function

c++,oop,friend,derived-class

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....

Loop by Object inside another Object in Java

java,list,oop,collections

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...

Check if object has given properties

php,oop

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:...

Class fields as method parameters

oop,groovy

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...

Bound mismatch: The type is not a valid substitute for the bounded parameter

java,oop,generics

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...

Avoiding type checking when interface method parameters are abstract

c#,oop,interface

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> { }...

Can adhering to the JavaBeans naming standard aid in achieving encapsulation?

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.

C# Code design / Seperate classes for each TabControl

c#,oop,architecture,software-design,code-design

Place a UserControl on each tab.

What is the proper way to use inheritance when combined with factory method?

oop,design-patterns

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.

Calling a method on array iteration, from an object - PHP

php,arrays,oop

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);...

Laravel5: Access public variable in another class

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...

Creating attribute defaults by calling a wrapped object

perl,oop,moose

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...

How access member function from arrayobject in a loop

c++,oop

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...

“Undefined method PDO::execute()” despite using prepare

php,oop,pdo,undefined

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"] )); ...

How to extract variable from one function into another in same class in php

php,oop,abstract-class

<?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...

Find method contents from a method in superclass? (Java/Eclipse)

java,eclipse,sockets,oop

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...

My simple php class not working [closed]

php,class,oop

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...

Why metaclass's __call__ method called on class, but native class's __call__ not?

python,oop,metaclass

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...

base class pointer, invoke method based on derived type

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(); }...

PHP classes - is it preferable to use normal variables instead of properties?

php,class,oop

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...

Nested pointer instead of inheritance

c++,oop,inheritance

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...

PHP mysqli_fetch_array() OOP style

php,oop,mysqli

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']; }...

Having issues with methods

java,oop,methods,constructor

You calling getUserChoice() in the pickWinner method. It should be the userChoice method parameter you should be checking. public String pickWinner(String userChoice, String cpuChoice) { String result = " "; if (userChoice.equalsIgnoreCase("rock")) { if (cpuChoice.equalsIgnoreCase("rock")){ result = "tie"; } else if (cpuChoice.equalsIgnoreCase("paper")){ result = "Computer"; } else if (cpuChoice.equalsIgnoreCase("scissors")){ result...

Calling an add on a list from a getter of an object does not work as expected

java,oop

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...

Solving a java riddle

java,class,oop,if-statement

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); } } } ...

Rails modeling headache

ruby-on-rails,oop,models

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. ...

Multidimensional array in class C++

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;...

Serial modification of objects in R

r,oop

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)...

Is dynamic_casting through inheritance hierarchy bad practice?

c++,oop,inheritance,casting

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,...

Why is 1_2_3_4 a valid integer literal in java? [duplicate]

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....

Nested objects in Python

java,python,oop

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 =...

Calling an object and its method from another object class method

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...

Python class design: explicit keyword arguments vs. **kwargs vs. @property

python,class,oop

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,...

Javascript: Access function within deep object on parse

javascript,oop,object

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

JavaScript oop: Designing classes correctly

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...

Why does the “this” keyword refer to the subclass too?

java,oop,this

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()...

Class variables in OOP

python,oop

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...

How to get the name of child class from base class when an object of child class is created

php,oop

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...

program that creates one main object and creates a pet for each of them [closed]

swift,oop

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 }...

Why there isn't library of design patterns?

java,oop,design-patterns

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...

How to transform a method call pattern found in multiple methods into a simpler OO mechanism?

php,oop,magic-methods,facade

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...

Automatic cast to subclass in getter/setter

java,oop

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...

Moving all fields info from one object to another

java,oop,object,field

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)...

How to get rid of duplicate code in derived classes?

c++,oop,inheritance,override

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(); }; }; ...

How to reuse this ViewController code in an object oriented way?

ios,objective-c,oop

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...

Force a child class to initialise a parent property after computation

c#,oop

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...

Can i use only _ (underscore) for the name of the class?

php,oop

Yes, you can use only underscore for the class name. class _{ function __construct(){ echo 'It works!'; } } new _(); Output: It works! DEMO...

How to avoid anemic data model? Can repositories be injected into entities?

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...

Interfaces in UML component diagram

oop,uml

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...

PHP Data Objetcs (PDO) example

php,mysql,oop,pdo

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...

How to implement repeated behavior when inheritance isn't an option

java,oop,interface

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 2.7 @property usage results in error “global name '_c__pro' is not defined”

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 ...

Is array of primitives assigned to variable as an Object (by reference) or by value?

java,arrays,oop

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,...

Why can't I call a method I define in a field? [duplicate]

java,oop,methods

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.

What is this thing called in Java?

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) {...

Where is the defination of rails validators?

oop,ruby-on-rails-4

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...

Calling on an implemented method automatically?

java,oop,implementation

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

Fatal error: Using $this when not in object context in E:\xampp\htdocs\

php,oop

$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); ...

Extending a method in PHP

php,oop

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...