OpenAI ChatGPT vs Google Bard for coding

Head-to-Head: A Quick Comparative report of ChatGPT and Google BARD’s Programming Capabilities

Xin Cheng
6 min readApr 24, 2023

Disclaimer: the subtitle is generated by ChatGPT (could use for title), inspired by this article.

Finally got access to Google Bard. Let’s use it to do coding to see how it compares to ChatGPT.

Java Spark

Prompt

generate a java spark program to read gdp below in csv file format, return latest 5 years GDP data for the country that has the highest GDP in most recent year. and returns the Country Name, Year, and GDP for each of those years:
columns are: Country Name,Country Code,Year,Value

ChatGPT

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class MainClass {
public static void main(String[] args) {
// Create a SparkSession
SparkSession spark = SparkSession.builder()
.appName("Java Spark GDP")
.master("local[*]")
.getOrCreate();

// Read the CSV file into a DataFrame
Dataset<Row> gdpData = spark.read()
.option("header", true)
.option("inferSchema", true)
.csv("/path/to/gdp/file.csv");

// Get the most recent year in the dataset
int maxYear = gdpData.selectExpr("max(Year)").collectAsList().get(0).getInt(0);

// Get the country with the highest GDP in the most recent year
Dataset<Row> topCountry = gdpData.filter("Year = " + maxYear)
.orderBy("Value DESC")
.limit(1);

// Get the top country's name
String countryName = topCountry.select("Country Name").collectAsList().get(0).getString(0);

// Filter for the most recent 5 years of data for the top country
Dataset<Row> recentGdpData = gdpData.filter("Country Name = '" + countryName + "'")
.filter("Year >= " + (maxYear - 4))
.orderBy("Year");

// Rename the Value column to GDP
recentGdpData = recentGdpData.withColumnRenamed("Value", "GDP");

// Select the columns to return
Dataset<Row> result = recentGdpData.select("Country Name", "Year", "GDP");

// Print the result
result.show();
}
}

Error: the only one is “orderBy(“Value DESC”)”, it is too “SQL”, it can be “ .orderBy(col(“Value”).desc())”

Quality: code is readable to a SQL person.

Google Bard

import org.apache.spark.sql.SparkSession;

public class GDP {

public static void main(String[] args) {

// Create a Spark session
SparkSession spark = SparkSession.builder()
.appName("GDP")
.master("local[*]")
.getOrCreate();

// Read the GDP CSV file
Dataset<Row> df = spark.read()
.option("header", true)
.csv("gdp.csv");

// Get the latest 5 years GDP data
df = df.where("Year >= 2018")
.orderBy("Value", ascending = false)
.limit(5);

// Get the country that has the highest GDP in most recent year
Row row = df.first();
String countryName = row.getString(0);
String countryCode = row.getString(1);
String year = row.getString(2);
Double value = row.getDouble(3);

// Get the latest 5 years GDP data for the country that has the highest GDP in most recent year
df = df.where("CountryName = '" + countryName + "'")
.where("Year >= 2018")
.orderBy("Year");

// Print the results
System.out.println("Country Name: " + countryName);
System.out.println("Country Code: " + countryCode);
for (Row r : df.collectAsList()) {
System.out.println("Year: " + r.getString(2) + " | GDP: " + r.getDouble(3));
}

// Close the Spark session
spark.close();
}
}

Issues

Missing

import org.apache.spark.sql.Dataset;

import org.apache.spark.sql.Row;

import org.apache.spark.sql.SparkSession;

import static org.apache.spark.sql.functions.*;

cannot find symbol class Dataset, class Row

Error

symbol: variable ascending

df = df.where(“Year >= 2018”)

.orderBy(“Value”, ascending = false)

Quality: code is not very readable.

Python FastAPI Restful API

Prompt

Can you create a Python FastAPI program for managing task, including all CRUD operations, follow the best practice of FastAPI? The task model has the following fields: id, title, description, creationdate, updatedate, duedate, completionrate

ChatGPT

Sure, I can help you with that. Here is a basic FastAPI program that implements CRUD operations for a Task model.

First, let's define the model in a separate file called `models.py`:

```python
from datetime import datetime
from typing import Optional
from pydantic import BaseModel


class TaskBase(BaseModel):
title: str
description: Optional[str] = None
duedate: Optional[datetime] = None
completionrate: Optional[int] = None


class TaskCreate(TaskBase):
pass


class TaskUpdate(TaskBase):
updatedate: Optional[datetime] = None


class Task(TaskBase):
id: int
creationdate: datetime

class Config:
orm_mode = True
```

Next, let's create a separate file for the database connection and operations called `database.py`:

```python
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./tasks.db"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
```

Then, we'll create a file called `main.py` for the main FastAPI application:

```python
from typing import List

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

from database import engine, SessionLocal, Base
from models import Task, TaskCreate, TaskUpdate

app = FastAPI()


# create the tables in the database
Base.metadata.create_all(bind=engine)


# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()


# CREATE operation
@app.post("/tasks/", response_model=Task)
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
db_task = Task(**task.dict(), creationdate=datetime.now())
db.add(db_task)
db.commit()
db.refresh(db_task)
return db_task


# READ operation (all tasks)
@app.get("/tasks/", response_model=List[Task])
def read_tasks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
tasks = db.query(Task).offset(skip).limit(limit).all()
return tasks


# READ operation (single task)
@app.get("/tasks/{task_id}", response_model=Task)
def read_task(task_id: int, db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task


# UPDATE operation
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, task: TaskUpdate, db: Session = Depends(get_db)):
db_task = db.query(Task).filter(Task.id == task_id)
if not db_task.first():
raise HTTPException(status_code=404, detail="Task not found")
db_task.update(task.dict(), synchronize_session=False)
db.commit()
return db_task.first()


# DELETE operation
@app.delete("/tasks/{task_id}", response_model=Task)
def delete_task(task_id: int, db: Session = Depends(get_db)):
db_task = db.query(Task).filter(Task.id == task_id)
if not db_task.first():
raise HTTPException(status_code=404, detail="Task not found")
db_task.delete(synchronize_session=False)
db.commit()
return db_task.first()
```

And that's it! This code should create a basic RESTful API for task management with CRUD operations. Here's a brief explanation of the code:

We define the Task model in models.py using the Pydantic BaseModel. It has fields for id, title, description, duedate, completionrate, and creationdate. We also define separate models for creating and updating tasks, as well as a Config class with orm_mode=True to allow us to use the model with an ORM like SQLAlchemy.

In database.py, we create an SQLite database using SQLAlchemy's create_engine function and define a SessionLocal object for managing database connections.

In main.py, we create a FastAPI application object and define the endpoints for the CRUD operations. We also define a get_db() function as a dependency for handling database connections. The @app.post endpoint creates a new task by adding a new Task object to the database with the current timestamp for the creationdate field. The @app.get endpoints retrieve all tasks or a single task by ID. The @app.put endpoint updates an existing task by ID, and the @app.delete endpoint deletes a task by ID.

We use FastAPI's response_model parameter to specify the response data for each endpoint as a Task object or list of Task objects.

We use SQLAlchemy's Session object to handle database transactions and queries within each endpoint. We also raise an HTTPException with a 404 status code and "Task not found" detail message if the requested task does not exist.

This code provides a basic starting point for a task management API with FastAPI and SQLAlchemy. However, you may want to customize it further to meet your specific needs, such as adding authentication or validation checks for input data.

Google Bard

from fastapi import FastAPI, HTTPException, Body, Query
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker

# Define the database schema
engine = create_engine('sqlite:///tasks.sqlite')
Session = sessionmaker(bind=engine)
session = Session()

# Define the task model
class Task(BaseModel):
id: int
title: str
description: str
creation_date: DateTime
update_date: DateTime
due_date: DateTime
completion_rate: int

# Define the FastAPI app
app = FastAPI()

# Define the CRUD operations
@app.post('/tasks')
async def create_task(task: Task):
session.add(task)
session.commit()
return task

@app.get('/tasks')
async def get_tasks():
tasks = session.query(Task).all()
return tasks

@app.get('/tasks/{id}')
async def get_task(id: int):
task = session.query(Task).get(id)
if not task:
raise HTTPException(status_code=404, detail='Task not found')
return task

@app.put('/tasks/{id}')
async def update_task(id: int, task: Task):
task_in_db = session.query(Task).get(id)
if not task_in_db:
raise HTTPException(status_code=404, detail='Task not found')
task_in_db.title = task.title
task_in_db.description = task.description
task_in_db.creation_date = task.creation_date
task_in_db.update_date = task.update_date
task_in_db.due_date = task.due_date
task_in_db.completion_rate = task.completion_rate
session.commit()
return task_in_db

@app.delete('/tasks/{id}')
async def delete_task(id: int):
task_in_db = session.query(Task).get(id)
if not task_in_db:
raise HTTPException(status_code=404, detail='Task not found')
session.delete(task_in_db)
session.commit()
return None

# Run the app
if __name__ == '__main__':
app.run(debug=True)

Both generated good code. However, ChatGPT seems to understand “follow best practice of FastAPI” to separate data model, database operations, API operations for better reusability, as described in this article.

--

--

Xin Cheng
Xin Cheng

Written by Xin Cheng

Multi/Hybrid-cloud, Kubernetes, cloud-native, big data, machine learning, IoT developer/architect, 3x Azure-certified, 3x AWS-certified, 2x GCP-certified

Responses (2)