oop,groovy , Class fields as method parameters

Class fields as method parameters


Tag: oop,groovy

My method needs to be strictly typed. If possible, I wanted to save some line of codes, setting the model properties from the parameter input by putting the model properties setter directly at the function definition.

The current working code:

class Connector {
  static def entityQuery(
    String httpMethod, 
    String typeName, 
    String orderFieldName,
    String orderOrderType,
    String orderOrderName
    EntityQuery model = new EntityQuery()
    model.httpMethod = httpMethod
    model.typeName = typeName
    model.order.fieldName = orderFieldname
    model.order.OrderType = orderOrderType
    model.order.OrderName = orderOrderName

    convertToMap( model )

wanted to achieve something like..

class Connector {

  static def entityQuery(
    String model.httpMethod, 
    String model.typeName, 
    String model.orderFieldName,
    String model.orderOrderType,
    String model.orderOrderName
    convertToMap( model )

There are many methods like entityQuery()


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 Connector.groovy will look like:

entityQuery( String httpMethod, EntityQuery entityQuery ) {
  // do something with httpMethod?
  convertToMap( entityQuery )

Sample use of entityQuery :

Connector connector = new Connector()
connector.entityQuery( "POST", new EntityQuery(typeName: "issue", order : new Order(fieldName : "title", orderType : "express", orderName : "meatOrder")))

for the constructor syntax see : http://www.groovy-lang.org/objectorientation.html#_constructors


Why has java kept length field in the jvm public

Here is an example: int[] a = {10}; int x = a.length; We read incessantly to hide variables and use accessors. Why was that rule violated here?...

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

First we have a property which is the array: private static $_errors = array(); An error can be added by sending it to a function, which will add it to the array: public function addError($error){ self::$_errors[] = $error; } In any function, I can easily add an error as a...

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

Code Explanation I have two classes, mesh and geometry, that are used to maintain attributes of a 3D array to fill a space. First a mesh is defined and builds a 3D array. Then geometric shapes can be created within the same bounds of the mesh object, but not in...

Decode base64 image in Grails [duplicate]

This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Spock's @Narrative and @Title annotations

Spock provides @Narrative and @Title annotations that you can use to provide a class-level description of your test, e.g. @Narrative('description of spec') @Title('title of spec') class ExampleSpec extends Specification { // tests omitted } What is the difference between these two? In other words, why do we need both of...

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

I want to get the name of my child class in the base class so that whenever an object of child class is created I get the name of the child class in my base class. Something like this: class Base_class { function __construct() { // Some code Here to...

creating multiple objects with browserify

I am trying to use the design pattern as below: human.js function Human(name){ this.name = name this.sayName = function(){ console.log(this.name); } } var a = new Human("bob"); var b = new Human("ted"); However I haven't used browserify much and I don't know how to do this in browserify. What I...

Rails modeling headache

I am in the process of building a Rails app that will let logged-in users: create multiple agendas access each agenda through a "month" view add events to each month share each agenda (through a link) with other logged-in users, who will see it with the same default "month" view...

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

This question already has an answer here: Calling newly defined method from anonymous class 5 answers Consider the following code. B.java public class B { void foo() { System.out.println("foo"); } } A.java public class A { B b = new B() { void lorem() { System.out.println("Lorem"); } }; void...

Spock Framework: problems with spying

I have an issue with using Spy in Spock, it either doesn't work as it should or my understanding is wrong so I'm trying to clarify this. Consider this code (Java): public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one...

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

I am new to swift coding and I was wondering how you would create a program that creates one main object and creates a pet for each of them. Would you use a string, array or what?

Passing variable data between classes OO Javascript

I am trying to create a basic app for creating and editing contact details - for the purposes of improving my JavaScript skills. For some reason I can't manage to pass variable data from one class to the next - I'm trying to implement something similar to an MVC just...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

I'm trying to set a cron Scheduled annotation as follows: @Scheduled(cron = "#{systemEnvironment['db_cron']}") def void schedule() { } Next set the environment variable as: export db_cron="0 19 21 * * *" However, I get the runtime error: Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}") What can...

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

Can i use only _ (underscore) for the name of the class if yes then how object will be create and if no then why not? class _{ } ...

Confused about the invokeMethod method in the Groovy MOP

First look at the following Groovy code: class Car { def check() { System.out.println "check called..." } def start() { System.out.println "start called..." } } Car.metaClass.invokeMethod = { String name, args -> System.out.print("Call to $name intercepted... ") if (name != 'check') { System.out.print("running filter... ") Car.metaClass.getMetaMethod('check').invoke(delegate, null) } def validMethod...

using classes in jenkins job dsl

Hi all I have a problem and I can't seem to figure it out. So I'm creating some helper classes for my dsl to use, but it just does not seem to execute any method within these classes. I have created a job with the following dsl in it: class...

sonar maven analysis only picks .java file

I am trying to run a sonar maven analysis on my multilanguage project which contains many languages like *.java, *.groovy, *.js etc. I have installed all the languages plugin in my sonar and configured my pom sonar.sources parameter as src/main,src/test but still it picks up only java files. In the...

Extending a method in PHP

I have two methods which are 90% identical, ie 90% repetitive code. I am trying to extend the 2nd method. First Method: public function getResultsByID($userID = null){ $sqlParams = array(); if (!$userID) { throw new Exception("No User ID Provided"); } $sqlParams['userID'] = $userID; $sql = "SELECT t.user_id, t.owner_id, t.store_id FROM...

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

In the following scenario, Main.registerEvents(Listener) is part of an event system of a game API. Let's say it should register any method with the @EventHandler annotation. public abstract class Spell implements Listener { protected Spell() { Main.getInstance().registerEvents(this); } @EventHandler public void onMove(PlayerMoveEvent event) { } } public class Fireball extends...

Groovy: run SQL SELECT LIKE from file with params

The groovy code is import groovy.sql.* dbUrl = 'jdbc:sqlserver://server' dbUser = 'username' dbPassword = 'password' dbDriver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver' sql = Sql.newInstance(dbUrl, dbUser, dbPassword, dbDriver) def sqlfromfile = new SqlFromFile() sqlfromfile.sql_filename='select_query.sql' sqlfromfile.read() try{ def result = sql.rows(sqlfromfile.result,[id:'01']) println result }catch(e){ println e } class SqlFromFile { def sql_filename def read(){ result=...

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

I am getting a Fatal Error while calling a public method using Scope Resolution Operator. Here is the part of the code: Class userrole { public function get_premium_subscritpion($userID) { $userID = ($userID == '') ? $this->user_info->ID : $userID; if (empty($userID)) return false; /* Check if user has subscribed */ if...

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

So I have an object with a list field and I am accessing the list using a getter. public class Customers{ private List<String> names; public Customers(List<String> names){ this.names = names; } public List<String> getNames(){ return names; } public String toString(){ StringBuilder sb = new StringBuilder(); for(String name: this.names){ sb.append("Customer:"); sb.append(name);...

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

Is there a generally accepted best practice for creating a class whose instances will have many (non-defaultable) variables? For example, by explicit arguments: class Circle(object): def __init__(self,x,y,radius): self.x = x self.y = y self.radius = radius using **kwargs: class Circle(object): def __init__(self, **kwargs): if 'x' in kwargs: self.x = kwargs['x']...

How access member function from arrayobject in a loop

I am trying to access public function get_data(), to generate an output "here ", to see if creating dynamic object from array of object..so how can i do that. #include<iostream> #include <conio.h> using namespace std; int counts = 0; int no_of_array; class Matrix { int **dynamicArray; public: Matrix() { counts++;...

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

I made 2 programs, one that works here: class dog: amount_of_dogs = 0 def __init__(self, name, playfulness): self.name = name self.playfulness = playfulness dog.amount_of_dogs += 1 dog1 = dog("Ruffer", 1000) dog2 = dog("Skipper", 400) dog3 = dog("El Diablo", 30000000) print "The dog names are:", dog1.name, ",", dog2.name, ",", dog3.name, "."...

Why there isn't library of design patterns?

I'm new to design pattern subject. If design pattern are so great, why can't someone build a library of them so I don't have to create them in each application?...

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

i have this classes hierarchy: public class Musician { private String name; public String instrument; public Musician(String name, String instrument) { this.name = name; this.instrument = instrument; } public String getName() { return name; } public String getInstrument() { return instrument; } private String getClassName() { return "Musician"; } public...

Loop by Object inside another Object in Java

I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

Java Design Issue: Enforce method call sequence

There is a question which was recently asked to me in an interview. Problem: There is a class meant to profile the execution time of the code. The class is like: Class StopWatch { long startTime; long stopTime; void start() {// set startTime} void stop() { // set stopTime} long...

Function pointer to singleton class instance function

What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

Laravel5: Access public variable in another class

I have a middleware file called LanguageMiddleware.php: ... class LanguageMiddleware { //ISO language codes: public $languages = ['en','es','fr','de','pt','pl','zh','ja']; ... LanguageMiddleware.php is in laravelProj/app/Http/Middleware/ Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages @foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang) <a class=\"setLang\" href=\"lang/en\">{{...

My simple php class not working [closed]

I wrote a simple class. but its not working. Something is wrong. can't find error line class Host { public $scheme; public $hostname; public $www; function __construct(string $scheme,string $hostname,string $www) { $this->scheme = $scheme; $this->hostname = $hostname; $this->www = $www; } public function get_URL() { return $this->scheme.'://'.$this->www.$this->hostname; } } $site...

Serial modification of objects in R

I have a number of matrices of the same size: m1.m <- matrix(c(1,2,3,4), nrow=2, ncol=2) m2.m <- matrix(c(5,6,7,8), nrow=2, ncol=2) ... I want to set uniform column and row names to all of them. Currently I am doing it like this: new_col_names <- c("Col1","Col2") new_row_names <- c("Row1","Row2") change_names <- function(m,...

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

Currently I have the following: public class ChildClass : ParentClass {... ParentClass implements an interface as follows (I need ParentClass to be instantiated and therefore can't be abstract): public class ParentClass : IParentClass {... I also want child class to implement an interface so that I can mock this class...

How to get testStep responseAsXml in groovyScript

Concerning soapUI and groovy, I'm trying to get assertion (working) and response both in XML into a variable. I get the error groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.getResponseAsXml() is applicable for argument types: () values: [] error at line: 6 I have tried adding import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep but still cant figure...

C# Code design / Seperate classes for each TabControl

My main problem is that my tool grows and grows and I start loosing the focus on the different parts of my code. The main-Form got a docked tabControl at fullsize. I got 5 different tabs with for really different functions. So I can say my tool is splitted into...

Get just content of soap response in Groovy

I have following soap response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetHTMLResponse xmlns="http://www.webserviceX.NET"> <GetHTMLResult> TEST </GetHTMLResult> </GetHTMLResponse> </soap:Body> </soap:Envelope> Now I want a method which deliverys me this xml: <root> <GetHTMLResponse...

Where is the defination of rails validators?

I am a beginner in rails. As I was working on rails validation, I wanted to know where is the definition of valid? and new_record? and all the validation helpers? I was trying to find the definition of all these functions but couldn't find any. Where do all this validations...

Groovy - timestamp from minutes

I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

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

class Meta(type): def __call__(cls, *args, **kwargs): print 'Meta.__call__ called.' return super(Meta, cls).__call__(*args, **kwargs) class MetaInstance(object): __metaclass__ = Meta # Instantiate class. MetaInstance() # Meta.__call__ called. class StandardClass(object): @classmethod def __call__(cls, *args, **kwargs): print 'StandardClass.__call__ called.' return super(StandardClass, cls).__call__(*args, **kwargs) # Instantiate class. StandardClass() # StandardClass.__call__ is not called! Why metaclass's...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Is dynamic_casting through inheritance hierarchy bad practice?

I have got the following data structure: class Element { std::string getType(); std::string getId(); virtual std::vector<Element*> getChildren(); } class A : public Element { void addA(const A *a); void addB(const B *b); void addC(const C *c); std::vector<Element*> getChildren(); } class B : public Element { void addB(const B *b); void...

Write Spock test cases for Spring boot application

I am working on spring boot application. I have to write test cases for it. I haven't written test cases before, so someone suggested using spock framework for it. I explored spock and i think it is more related to groovy language. Can i write spock test cases for my...

PHP mysqli_fetch_array() OOP style

I want to run a SELECT query and fetch data as associative array and echo the fetched data. In procedural style I would use mysqli_fetch_array(). But I am now trying OOP style. I have tried this code: $con= new mysqli('localhost','root','','afiliate'); $query="SELECT * FROM product WHERE ID=? "; $stmt->bind_param("i",$ID); /* $ID...

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

This code has been working before, but I recently added a database class. I get the instance and connection from it: $connection = MYSQLDatabase::getInstance()->getConnection(); $connection->prepare("INSERT INTO users etc etc....... $insertArray = $connection->execute(array( ":username" => $_POST["username"] )); getInstance() returns the database instance. getConnection() returns the connection property which contains: new PDO('mysql:host='...

groovy/XML: Replace a node by another one

I try to replace an XML node by another one by using XmlSlurper (or XmlParser). The original XML: <myXml> ... <myNode> <Name>name1</Name> <Name>name2</Name> <Name>name3</Name> </myNode> ... </myXml> The list that contains the items to build my new node def namelist = ['name4','name5','name6','name7'] What I want to have <myXml> ... <myNode>...

PHP Data Objetcs (PDO) example

I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing). <?php...

JavaScript Functional Classes [closed]

I am learning object oriented programming in JavaScript from an Udacity course. I would like to know which among the below is the best technique to create an Functional Object and why. First code: var Car = function(loc){ var Obj = {loc:loc}; extend(Obj, Car.methods); return Obj; } Car.methods = {...

Special Groovy magic re property access and collections / iterables?

I understand what is happening here with the spread operator *. in Groovy (2.4.3): [].class.methods*.name => [add, add, remove, remove, get, ... But why does the leaving the * out produce the same results? [].class.methods.name => [add, add, remove, remove, get, ... I'd have expected that to be interpreted as...

Model to LazyMap

How do I convert/deserialize these models public class AccessCredentials { String userName = '' String password = '' LoginOptions loginOptions = new LoginOptions() } public class LoginOptions { String partnerId = '' String applicationId = '' } into a LazyMap like : [ userName : userName, password : password, loginOptions...